Laravel eloquent 获取关系计数

新手上路,请多包涵

我使用 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 许可协议

阅读 319
2 个回答

您可以使用 withCount() 。从 5.3 版本开始提供

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

原文由 kapilpatwa93 发布,翻译遵循 CC BY-SA 3.0 许可协议

关于 Carlos_E. 的回答。您可以使用 whereHas 而不是 whereIn 来改进查询:

 $agents = Agents::whereHas('schedule')
)->with('schedules')->get();

原文由 Jeppe Theis Gyntzel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题