【问题标题】:Laravel eloquent: HasManyThrough of HasManyThrough relationship?Laravel 雄辩:HasManyThrough 的 HasManyThrough 关系?
【发布时间】:2018-07-24 00:28:32
【问题描述】:

这可能吗?

关系:
类别有许多类别板
CategoryBoards 有很多线程
CategoryBoards hasMany threadPosts THROUGH threads

视觉关系:
https://imgur.com/dtrZ0cO
https://imgur.com/a/1aVAs

我想获取主题的数量和类别的主题帖子。

在我的类别中,由于线程关系,我可以计算线程数。 但是对于线程帖子,我不知道如何将其与类别联系起来。我在下面尝试了一些方法,但它不起作用。

//CATEGORY CLASS

    public function threads() {
    return $this->hasManyThrough(
        'App\Models\Views\ThreadView',
        'App\Models\Views\CategoryBoardView',
        'categoryId',
        'categoryBoardId',
        'categoryId',
        'categoryBoardId'
    );
}

//doesnt work
public function threadPosts() {
    return $this->hasManyThrough(
        'App\Models\Views\ThreadPostView',
        $this->threads(),
        'categoryBoardId',
        'threadId',
        'categoryId',
        'threadId'
    );
}

我的查询目前如下所示:

            $returnData['categories'] = CategoryView::with('categoryBoards')
            ->withCount('threads AS threadCount')
            ->get();

【问题讨论】:

  • 我对这么多关系感到困惑,您能否从迁移中添加代码,以便我们可以查看所有字段以及您可以建立哪些可能的关系
  • 添加了一张图片。
  • 您需要添加一个模型 CategoryBoards ,您将在其中放置通过线程获取线程帖子的函数 threadPosts
  • 我已经有了。
  • hasmanythrough 不能深入 4 个课程,但可以算第四级,就像@vpalade 提到的那样,为什么需要第四级是问题?

标签: laravel eloquent


【解决方案1】:

试试这个:

$returnData['categories'] = CategoryView::with(['categoryBoards' => function($q){
                 $q->withCount('threadPosts');
            }])
            ->withCount('threads AS threadCount')                
            ->get();

threadPosts 关系将在 CategoryBoards 模型中

threadPosts_count 应该在每个 categoryBoards 对象中

【讨论】:

  • ->withCount('categoryBoards.threadPosts AS threadPostsCount') 这不起作用。我认为您无法计算急切加载的关系。
  • 你能在问题中显示控制器和关系
  • 嗨,我把 ->withCount('threads AS threadCount') 放在了闭包中,它起作用了。
【解决方案2】:
$returnData['categories'] = CategoryView::with(['categoryBoards' => function($query) {
        $query->withCount(['threads AS threadCount', 'threadPosts AS threadPostCount']);
    }])->get();

感谢@vplade

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2018-10-18
    • 2023-03-09
    • 2018-09-25
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多