Laravel中如何根据关联产品的type请求参数筛选Category模型关联数据
Laravel 关联查询实现方案
首先获取请求的type参数,再通过嵌套whereHas实现跨两层关联的条件过滤:
$type = $request->input('type'); $categories = Category::whereHas('products.type', function ($query) use ($type) { // 这里的id替换为你type表实际需要匹配的字段,比如name、slug等 $query->where('id', $type); }) // 如果需要返回结果中附带关联的products和对应type数据,保留下面这行,不需要可删除 ->with('products.type') ->get();
如果需要同时过滤返回的products列表,只保留符合type条件的产品,使用带约束的with查询:
$type = $request->input('type'); $categories = Category::whereHas('products.type', function ($query) use ($type) { $query->where('id', $type); })->with([ 'products' => function ($query) use ($type) { $query->whereHas('type', function ($q) use ($type) { $q->where('id', $type); }); }, 'products.type' ])->get();
补充说明:
whereHas('products.type')是Laravel提供的点语法嵌套关联查询简写,等价于嵌套两层whereHas分别查询products和type关联- 如果你的type参数是type模型的主键ID,直接用
where('id', $type)性能最优,不需要额外关联字段匹配
内容的提问来源于stack exchange,提问作者Mehdi Yaghoubi
相关产品推荐
相关产品推荐

