You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eloquent关联三张表查询中WHERE子句的使用咨询

在Eloquent三层关联查询中添加WHERE子句的方法

嘿,我来帮你搞定这个问题!根据你要过滤的是主表还是关联表,咱们分几种常见情况来写对应的查询:

1. 过滤主表(TCategory)的字段

如果是要筛选主表TCategory的某个字段,直接在with()之前加where()就行,非常直观:

$truck = TCategory::where('name', 'western') // 筛选name为western的分类
    ->with('truck_categories.touch_points')
    ->get();

// 保持你原来的返回逻辑不变
if(count($truck) > 0) {
    return response()->json(array('result' => $truck));
} else {
    return response()->json(array('result' => 'No Trucks.'));
}

2. 过滤中间关联表(truck_categories)的字段

如果要筛选存在符合条件的truck_categories的TCategory,得用whereHas()方法,它会过滤出关联关系满足条件的主表记录:

$truck = TCategory::whereHas('truck_categories', function($query) {
        $query->where('touch_point_id', 8); // 筛选touch_point_id为8的关联记录
    })
    ->with('truck_categories.touch_points')
    ->get();

3. 过滤最底层关联表(touch_points)的字段

如果要基于最底层的touch_points表字段过滤主表,直接在whereHas()里写嵌套的关联路径就行:

$truck = TCategory::whereHas('truck_categories.touch_points', function($query) {
        $query->where('name', 'like', '%delivery%'); // 筛选touch_points中name包含delivery的记录
    })
    ->with('truck_categories.touch_points')
    ->get();

4. 只加载符合条件的关联数据(不过滤主表)

如果你不想过滤主表,只是想在加载关联的时候只取符合条件的部分,那就在with()里用闭包来限制关联数据:

// 只加载touch_point_id为8的truck_categories,以及对应的touch_points
$truck = TCategory::with([
    'truck_categories' => function($query) {
        $query->where('touch_point_id', 8);
    },
    'truck_categories.touch_points'
])->get();

// 甚至可以进一步过滤touch_points
$truck = TCategory::with([
    'truck_categories' => function($query) {
        $query->where('touch_point_id', 8)
              ->with(['touch_points' => function($subQuery) {
                  $subQuery->where('status', 'active'); // 只加载状态为active的touch_points
              }]);
    }
])->get();

你可以根据自己的实际需求,选择上面对应的写法替换原来的查询部分就好啦!

内容的提问来源于stack exchange,提问作者Hashaam Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:18:08