Laravel 中 withCount 统计嵌套关联数据

admin 阅读:46 2024-03-02

假设有如下模型关系:

Tutorial -> (hasMany) Chapters -> (hasMany) videos

我想在 Tutorial 模型中使用 withCount 统计 videos 的数量要怎么实现?

解决办法:

方法1:通过远程一对多关联关系统计。

模型定义如下关系:

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

    function videos()
    {
        return $this->hasManyThrough(Video::class, Chapter::class);
    }
}

调用:

Tutorial::withCount(['videos']);

方法2:通过闭包函数方式

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

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!