我使用 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');
但是我迷路了……
原文由 Vincent Decaux 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
withCount()
。从 5.3 版本开始提供有关 eloquent 的更多信息,请访问: https ://laravel.com/docs/5.3/eloquent-relationships