我具有以下功能,可以从表Product_Colors
中查找具有相同颜色的产品,并且效果很好:
$colors = ProductColor::query()->
select('color_id', DB::raw("count(*) as amount"))
->groupBy('color_id')
->having('amount','>=', '3')
->get();
我有很多对很多关系:
public function colors() {
return $this->belongsToMany('App\Color','product_colors');
}
现在我要获得具有相同3种颜色的每种产品。 我有这个查询:
$products = Product::whereHas('colors', function(Builder $query) { $query
->groupBy('color_id', 'product_id');},'>', '3')->get();
,我什么也没得到,但是我确定我有两种具有3种相同颜色的产品。有人可以帮我提示我做错了什么吗?
我有以下代码来获取所有具有3种以上颜色的项目:
$products = Product::has('colors', '>', 3)->with('colors')->get();
但是我需要所有超过3种颜色且颜色完全相同的颜色 例如:
"products": [
{
"id": 2,
"title": "net",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"colors": [
{
"id": 16,
"name": "Peru",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 2,
"color_id": 16
}
},
{
"id": 17,
"name": "Red",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 2,
"color_id": 17
}
},
{
"id": 20,
"name": "DarkTurquoise",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 2,
"color_id": 20
}
},
{
"id": 2,
"name": "MediumPurple",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 2,
"color_id": 2
}
}
]
},
{
"id": 3,
"title": "org",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"colors": [
{
"id": 2,
"name": "MediumPurple",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 3,
"color_id": 2
}
},
{
"id": 16,
"name": "Peru",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 3,
"color_id": 16
}
},
{
"id": 17,
"name": "Red",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 3,
"color_id": 17
}
},
{
"id": 20,
"name": "DarkTurquoise",
"created_at": "2019-10-08 07:36:42",
"updated_at": "2019-10-08 07:36:42",
"pivot": {
"product_id": 3,
"color_id": 20
}
}
]
},
答案 0 :(得分:1)
我认为您不能像这样对where子句提供检查。
因此,请尝试以下操作:
$products = Product::whereHas('colors', function(Builder $query)
{
$query->groupBy('color_id', 'product_id')
->havingRaw('count(color_id) > 3');
})
->with('colors') // eager load them
->get();
它可能无法正常运行,因为我无法尝试,但我希望它至少可以使您了解如何执行此操作。
否则,请在collection实例上使用过滤器。
所以可能是这样的:
$products = Product::has('colors')->with('colors')
->get()
->filter(function($item) {
return $item->colors->count() >= 3;
});