Laravel关联查询:如何仅返回符合指定年月条件的Traffic关联模型
解决Laravel关联查询仅加载指定条件关联数据的问题
你当前的问题是whereHas只负责筛选出存在符合条件Traffic记录的Salesperson,但with("traffic")会加载该Salesperson的所有Traffic关联数据,而非仅符合指定年月条件的部分。
要实现只返回目标年月的Traffic数据,需要给with方法里的traffic关联添加过滤闭包,和whereHas里的筛选条件保持一致,这样就能同时完成Salesperson的筛选和关联数据的精准过滤。
修改后的代码如下:
// 简化日期处理,用Laravel内置的Carbon实例更便捷 $date = now()->setTimezone("America/New_York"); $month = $date->format("m"); $year = $date->format("Y"); $salespeople = Salesperson::with([ 'store', 'traffic' => function ($query) use ($month, $year) { // 给traffic关联数据添加年月筛选条件 $query->whereMonth("date_for", $month)->whereYear("date_for", $year); } ])->whereHas("traffic", function ($query) use ($month, $year) { $query->whereMonth("date_for", $month)->whereYear("date_for", $year); })->get();
补充优化提示:
- 这里将
with的参数改为数组形式,对traffic关联单独配置过滤逻辑,store关联不受影响正常加载; - 若你的Laravel版本支持,也可以用
whereBetween指定当月完整日期范围,这种写法更利于利用date_for字段的索引,性能更优:
$startOfMonth = $date->startOfMonth(); $endOfMonth = $date->endOfMonth(); $query->whereBetween("date_for", [$startOfMonth, $endOfMonth]);
内容的提问来源于stack exchange,提问作者Chris Lamb
相关产品推荐
相关产品推荐

