【发布时间】:2017-05-01 03:33:30
【问题描述】:
我使用 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');
但我迷路了……
【问题讨论】:
-
表
category中有多少层次结构? -
最多只有 2 个,不能更多