首页  >  问答  >  正文

查找交易到期日期的方法在关联表中

我有一个分类表,其中包含不同的交易类别。每个类别都包含许多交易以及它们的到期日期。我想只访问那些到期日期尚未过期的交易和它们的类别,但我遇到了一个问题,即如果某个类别的交易在时间范围内存在,那么所有的交易都会到达,无论它们是否过期。这是我的代码:

$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粉752812853P粉752812853372 天前527

全部回复(1)我来回复

  • P粉042455250

    P粉0424552502023-09-14 13:55:18

    当你使用with来加载关联关系时,你可以传递额外的条件告诉Eloquent要加载哪些记录:

    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);

    最新版本的Laravel甚至包括了一个专门的withWhereHas方法,可以在同时加载关联关系的同时检查关系的存在性,基于相同的条件进行加载:

    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);

    任何一种选项都可以满足你的需求。

    回复
    0
  • 取消回复