我有一个分类表,其中包含不同的交易类别。每个类别都包含许多交易以及它们的到期日期。我想只访问那些到期日期尚未过期的交易和它们的类别,但我遇到了一个问题,即如果某个类别的交易在时间范围内存在,那么所有的交易都会到达,无论它们是否过期。这是我的代码:
$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); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
当你使用
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);任何一种选项都可以满足你的需求。