Laravel雄辩地获得关系计数 [英] Laravel eloquent get relation count
本文介绍了Laravel雄辩地获得关系计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Laravel 5.3.
I use Laravel 5.3.
我有2张桌子:
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');
}
是否有使用Eloquent的简单方法来列出带有文章计数的类别.困难之处在于,我想对 id_parent = 0
的类别进行分组,即,我只想显示带有孩子文章数的父类别.
Is there an easy way using Eloquent to have a list a categories with count of articles. The difficulty is that I want to group categories where id_parent = 0
, i.e. I want to display only parent categories with count of articles in 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');
但是我迷路了...
推荐答案
您可以使用 withCount()
.从5.3版本开始可用
you can use withCount()
. It is available from 5.3 version
有关口才访问的更多信息: https://laravel.com/docs/5.3/eloquent关系
for more info about eloquent visit : https://laravel.com/docs/5.3/eloquent-relationships
这篇关于Laravel雄辩地获得关系计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文