Laravel 雄辩地获得关系计数
我使用Laravel 5.3。
我有2张桌子:
Articles
---------
id
cat_id
title
和
Category
---------
id
parent_id
title
我已经在我的模型中定义了我的关系:
// Article model
public function category()
{
return $this->belongsTo(Category::class);
}
// Category model
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
有没有一种简单的方法使用Eloquent来列出一个包含文章计数的类别。困难在于,我想将类别分组,即我只想显示父类别,并显示子类别中的文章计数。id_parent = 0
我尝试了这样的东西:
$category = new \App\Models\Category();
$categoryTable = $category->getTable();
return $category->leftJoin('article', 'article.cat_id', '=', 'category.id')
->whereIn('article.cat_id', function($query)
{
$query->select('cat_id')
->from('categories')
->where('categories.parent_id', ???)
->orWhere($this->tableName .'.cat_id', $id);
})
->groupBy('cat_id');
但是我迷路了...