Laravel中按产品组分组获取匹配属性查询的产品集合问题
问题描述
需要获取product_groups集合,每个产品组下仅包含满足product.attributes关联查询条件的products,示例如下:
- 产品组A
- 产品1(匹配查询值)
- 产品2(匹配查询值)
- 产品组B
- 产品3(匹配查询值)
- 产品组C
- 产品4(匹配查询值)
当前使用以下代码能获取到正确的product_groups,但每个组中返回的是该组下所有产品,而非仅匹配条件的产品:
$product_groups = ProductGroup::with('products') ->whereHas('products.attributes', function($query) use ($value) { $query->where('value', $value); }) ->get();
目标是为每个product_groups展示表格,列出匹配查询值的产品及其他信息,需在blade文件中使用product_group和products的属性。
解决方案
问题出在with('products')会加载该产品组下的所有产品,而whereHas仅用于筛选存在匹配产品的组,不会过滤关联的产品列表。要同时过滤关联的产品,需要在with的闭包里添加相同的筛选条件:
$product_groups = ProductGroup::with(['products' => function($query) use ($value) { // 筛选出满足属性条件的产品 $query->whereHas('attributes', function($subQuery) use ($value) { $subQuery->where('value', $value); }); }]) ->whereHas('products.attributes', function($query) use ($value) { $query->where('value', $value); }) ->get();
这样处理后,每个product_group下的products集合就只包含满足attributes查询条件的产品了。
Blade视图示例
在blade文件中可按以下方式遍历展示:
@foreach($product_groups as $group) <h3>{{ $group->name }}</h3> <table> <thead> <tr> <th>产品名称</th> <th>其他信息</th> </tr> </thead> <tbody> @foreach($group->products as $product) <tr> <td>{{ $product->name }}</td> <td>{{ $product->other_info }}</td> </tr> @endforeach </tbody> </table> @endforeach
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

