繁体   English   中英

Laravel雄辩的联接表和计数相关

[英]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')

  1. 你有错字
  2. 还要添加表'categories.id', '=', 'products.category_id'

如果您正在使用模型,应该使用... @DigitalDrifter具有“口才”解决方案。

两个助手

  1. 我将避免在别名中使用mysql保留字。 改为使用COUNT(product.id) AS product_count
  2. 您可以使用传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM