我使用 Laravel 5.3。
我有 2 张 table :
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');
但是我迷路了...
最佳答案
您可以使用 withCount()
.从 5.3 版本开始可用
有关 Eloquent 访问的更多信息:https://laravel.com/docs/5.3/eloquent-relationships
关于php - Laravel eloquent 获取关系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165726/