I have a classification table with different transaction categories. Each category contains a number of transactions along with their expiry dates. I want to access only those transactions and their categories whose expiry date has not yet expired, but I'm running into an issue where if transactions of a certain category exist within the time range, then all transactions will arrive regardless of whether they have expired or not. This is my code:
$deals = DealCategory::where('name', '!=', '今日交易') ->whereRelation('deals','start_date', '<=', date('Y-m-d')) ->whereRelation('deals', 'expiry_date',">=", date('Y-m-d')) ->with('deals', 'deals.deal_images', 'deals.deal_products', 'deals.deal_products.product', 'deals.rating')->latest()->Paginate(12); return response()->json(['Deals' => $deals, 'Date' => Carbon::now(), 'status' => 'success'], 200);
P粉0424552502023-09-14 13:55:18
When you use with
to load a relationship, you can pass additional conditions to tell Eloquent which records to load:
DealCategory::where('name', '!=', 'Today Deal') ->whereRelation('deals','start_date', '<=', date('Y-m-d')) ->whereRelation('deals', 'expiry_date',">=", date('Y-m-d')) ->with(['deals' => function ($query) { $query->where('start_date', '<=', date('Y-m-d')); $query->where('expiry_date',">=", date('Y-m-d')); $query->with('deal_images', 'deal_products', 'deal_products.product', 'rating'); }]) ->latest()->Paginate(12);
The latest version of Laravel even includes a dedicated withWhereHas
method, which can check the existence of the relationship while loading the relationship at the same time, loading based on the same conditions:
DealCategory::where('name', '!=', 'Today Deal') ->withWhereHas('deals', function ($query) { $query->where('start_date', '<=', date('Y-m-d')); $query->where('expiry_date',">=", date('Y-m-d')); $query->with('deal_images', 'deal_products', 'deal_products.product', 'rating'); }) ->latest()->Paginate(12);
Any option can meet your needs.