【问题标题】:Laravel 5.3 withCount() nested relationLaravel 5.3 withCount() 嵌套关系
【发布时间】:2016-09-22 08:14:11
【问题描述】:

模型结构如下

教程 -> (hasMany) 章节 -> (hasMany) 视频

我们如何使用 laravel 5.3 的 withCount() 方法从教程模型中加载视频数量(video_count)

我试过了:

Tutorial::withCount('chapters')
->withCount('chapters.videos') // this gives error: Call to undefined method Illuminate\Database\Query\Builder::chapters.videos()
->all();

编辑

这行得通,还有更好的解决方案吗?

Tutorial::withCount('chapters')
->with(['chapters' => function($query){
    $query->withCount('videos');
}])
->all();

【问题讨论】:

  • 你在模型中定义了关系吗?
  • 你只需要做一个 ->withCount('chapters.videos')。另外,请确保您的关系设置正确。
  • @DigitalFire 关系是正确的,因为我可以通过急切加载来加载它们。只是 count 不填充 withCount() 方法
  • 请在答案部分发布您的编辑。我只是更喜欢这样做。

标签: php eloquent laravel-5.3


【解决方案1】:

您只能对模型的定义关系执行withCount()

但是,关系可以是hasManyThrough,这将实现您的目标。

class Tutorial extends Model
{
    function chapters()
    {
        return $this->hasMany('App\Chapter');
    }

    function videos()
    {
        return $this->hasManyThrough('App\Video', 'App\Chapter');
    }
}

然后你可以这样做:

Tutorial::withCount(['chapters', 'videos'])

文档:

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2014-10-27
    • 2020-08-11
    • 2021-07-19
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多