Laravel eloquent get relation count

前端 未结 5 2027
温柔的废话
温柔的废话 2021-02-05 00:29

I use Laravel 5.3.

I have 2 tables :

Articles
---------
id
cat_id
title

And

Category
---------
id
parent_id
title
         


        
5条回答
  •  粉色の甜心
    2021-02-05 01:03

    This should work:

    $category
    ->where('categories.parent_id', 0)
    ->leftJoin('article', 'article.cat_id', '=', 'categories.id')
    ->select('categories.id', \DB::raw('COUNT(article.id)'))
    ->groupBy('categories.id')
    ->get();
    

    The above query will get you category IDs and count of all articles that belong to the category.

    After reading your question and comments again, if I understand correctly you want to get the count of all articles that belong to those categories (with parent_id = 0) + the count of articles that belong to sub categories (those with parent_id = (id of some category)).

    Now I have no way of testing this easily, but I think something along these lines should work for that.

    $category
    ->where('categories.parent_id', 0)
    ->leftJoin('article', 'article.cat_id', '=', 'categories.id')
    ->leftJoin('categories as c2', 'c2.parent_id', '=', 'categories.id')
    ->leftJoin('article as a2', 'a2.cat_id', '=', 'c2.id')
    ->select('categories.id', \DB::raw('(COUNT(article.id)) + (COUNT(a2.id)) as count'))
    ->groupBy('categories.id')
    ->get();
    

    That beign said, I think you're better of having a column named count in categories and update it each time a new article gets added. For performance.

提交回复
热议问题