我用的是Laravel 5.3.
I have 2 tables :
Articles
---------
id
cat_id
title
和
Category
---------
id
parent_id
title
I have defined my relations in my models :
// Article model
public function category()
{
return $this->belongsTo(Category::class);
}
// Category model
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
有没有一种简单的方法用口才有一个列表和文章数量的分类.困难之处在于,我想要将id_parent = 0
个类别分组,即我只想显示带有 children 文章计数的父类别.
我试过这样的方法:
$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');
但是我迷路了.