在laravel中检查一对多关系中的计数
我有产品表,每个产品都有很多订单,在laravel中检查一对多关系中的计数,laravel,Laravel,我有产品表,每个产品都有很多订单,product.php public function orders() { return $this->hasMany(Order::class,'product_id'); } 我可以通过以下代码获得按订单数量订购的产品: $products = Product::withCount('orders')->orderBy('orders_count', 'desc')->get(); 现在我想让控制器中的产品订单数量大
product.php
public function orders()
{
return $this->hasMany(Order::class,'product_id');
}
我可以通过以下代码获得按订单数量订购的产品:
$products = Product::withCount('orders')->orderBy('orders_count', 'desc')->get();
现在我想让控制器中的产品订单数量大于5,
我该怎么做呢?下面的代码应该只给出计数大于5的订单
$products = Product::withCount('orders')->where('orders_count', '>', 5)->orderBy('orders_count', 'desc')->get();
添加->where()
就可以了
希望有帮助
更新
试一试
这应该适用于获得订单数超过5的产品。下面的代码应该只提供数量大于5的订单
$products = Product::withCount('orders')->where('orders_count', '>', 5)->orderBy('orders_count', 'desc')->get();
添加->where()
就可以了
希望有帮助
更新
试一试
这应该可以获得订单超过5个的产品。一种方法是使用: 我认为文档中没有提到它,但您不必将闭包作为第二个参数传递,第三个和第四个参数可用于传递运算符和计数
或者,您可以使用:
一种方法是使用: 我认为文档中没有提到它,但您不必将闭包作为第二个参数传递,第三个和第四个参数可用于传递运算符和计数
或者,您可以使用:
您可以对集合使用映射来筛选记录,例如:`
$collection = collect($products)->map(function ($product) {
return $product->orders->count() > 5;
})
->reject(function ($name) {
return $product->orders->count() < 5;
});`
$collection=collect($products)->map(函数($product){
返回$product->orders->count()>5;
})
->拒绝(函数($name){
返回$product->orders->count()<5;
});`
这只是一个例子,如果需要,您可以设置更多条件。
希望这能有所帮助。您可以在收藏中使用映射来筛选记录,例如:`
$collection = collect($products)->map(function ($product) {
return $product->orders->count() > 5;
})
->reject(function ($name) {
return $product->orders->count() < 5;
});`
$collection=collect($products)->map(函数($product){
返回$product->orders->count()>5;
})
->拒绝(函数($name){
返回$product->orders->count()<5;
});`
这只是一个例子,如果需要,您可以设置更多条件。
希望这有帮助。不幸的是,这不起作用,因为您不能在where子句中使用别名,但是,您可以使用
having()
。不幸的是,这不起作用,因为您不能在where子句中使用别名,但是,您可以使用having()
。
$collection = collect($products)->map(function ($product) {
return $product->orders->count() > 5;
})
->reject(function ($name) {
return $product->orders->count() < 5;
});`