Laravel eloquent get relation count

前端 未结 5 2014
温柔的废话
温柔的废话 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:01

    Define a articles() relation in your Category model as:

    public function articles() 
    {
        return $this->hasMany(Article::class, 'cat_id');
    }
    

    Then you can try it as:

    Category::where('parent_id', 0)->withCount('articles')->get();
    

提交回复
热议问题