以下是我必須提取所有Discussions
及相關聯的threads
和posts
的代碼。我試圖限制帖子的數量爲1.當我這樣做時,我希望每個線程只有1個帖子,但是9個線程沒有帖子,1個帖子有1個帖子。Laravel:限制嵌套關係
App\Discussion::with([
'threads' => function ($query) => {
// Correctly limits the number of threads to 10.
$query->latest()->take(10);
},
'threads.posts' => function ($query) {
// Limits all posts to 1, not each post to 1 for each thread.
$query->take(1);
}
])->where(['slug' => 'something'])->firstOrFail();
上面的代碼在數據庫中運行以下SQL查詢。
select * from `discussions` where (`slug` = ?) and `discussions`.`deleted_at` is null limit 1
select * from `threads` where `threads`.`discussion_id` in (?) and `threads`.`deleted_at` is null order by `created_at` desc limit 10
select * from `posts` where `posts`.`thread_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and `posts`.`deleted_at` is null order by `created_at` desc limit 1
我可以看到第三個查詢是一個引起,因爲它是限制所有帖子爲1
我希望看到下面的問題;一個討論,在該線程中有10個線程和1個帖子。
{
"id": 1,
"title": "Discussion Title",
...
"threads": [
{
"id": 1,
"title": "Thread Title",
...
"posts": [
{
"id": 1,
"title": "Post Title",
...
}
]
}
...
]
}
有沒有辦法在Laravel框架內執行此操作,還是需要運行原始查詢?我寧願儘可能地堅持雄辯的ORM。
請顯示您的線程模型代碼,特別是「public function posts()」。它是多對多還是一對多關係? –