Method to find transaction expiry date in related table
P粉752812853
P粉752812853 2023-09-13 16:19:38
0
1
666

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粉752812853
P粉752812853

reply all(1)
P粉042455250

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template