Laravel 雄辩地获得关系计数

2022-08-30 09:10:31

我使用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');

但是我迷路了...


答案 1

您可以使用 .它从5.3版本开始可用withCount()

有关雄辩访问的更多信息:https://laravel.com/docs/5.3/eloquent-relationships


答案 2

在模型中定义关系为:articles()Category

public function articles() 
{
    return $this->hasMany(Article::class, 'cat_id');
}

然后,您可以尝试如下操作:

Category::where('parent_id', 0)->withCount('articles')->get();

推荐