Laravel雄辩:HasMany通过HasManyThrough关系?

时间:2018-02-13 15:25:11

标签: laravel eloquent

这可能吗?

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

视觉关系:
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();

2 个答案:

答案 0 :(得分:0)

试试这个:

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

threadPosts关系将位于CategoryBoards模型

threadPosts_count应位于每个categoryBoards对象

答案 1 :(得分:0)

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

致@vplade的信用