다음은 모두 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 프레임 워크에서이를 수행 할 방법이 있습니까, 아니면 원시 쿼리를 실행해야합니까? Eloquent ORM을 가능한 한 많이 사용하고 싶습니다.
스레드 모델 코드, 구체적으로 "public function posts()"를 표시하십시오. 그것은 다 대다 또는 일대 다 관계입니까? –