[英]Laravel 5.3 Eloquent Join table with multiple condition join having count
[英]Laravel Eloquent join table and count related
我有两个表,类别和产品。 我正在尝试添加一个查询,以对每个类别的产品进行计数,而不用对每个类别进行分类。 我到达以下查询:
DB::table('categories')->leftJoin('product', 'categories.id', '=','categpry_id')
->selectRaw('categories.*, count(product.id) as Count')
->where('product.status',1)
->groupBy('categories.id')
->get();
但是我面临的问题是,当某个类别没有产品时,它就不会显示出来。 我想显示没有产品的类别,数组中有0个产品。
我很确定您可以为此使用rightJoin
。
虽然不是100%肯定。
您可以使用Eloquent的withCount
方法:
$categories = Category::withCount('products')->get();
每个$category
将具有一个products_count
属性。
'categories.id', '=','categpry_id')
'categories.id', '=', 'products.category_id'
如果您正在使用模型,应该使用... @DigitalDrifter具有“口才”解决方案。
COUNT(product.id) AS product_count
。 select
的数组来最小化原始语句。 Categories::leftJoin(Product::class, 'product.category_id', '=', 'categories.id')
->select([
'categories.*',
DB::raw('COUNT(products.id) AS product_count')
])
->where('product.status', 1)
->groupBy('categories.id')
->get();
Model::withCount('relation')
也很酷。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.