Last active
December 4, 2018 11:56
-
-
Save euoia/2b64b4fc77e6c448d6f1a7dffea8874a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Schema: | |
Post hasMany Threads | |
Thread hasMany Comments | |
# Problem | |
In this made up example, I'm selecting all posts, threads and comments that | |
have comments by a particular user. I'm not interested in the other threads, or | |
the other comments, just the Post data, Thread data and Comments for comments by | |
this user. In SQL this is easy: | |
SELECT | |
* | |
FROM | |
`posts` | |
INNER JOIN `threads` ON `threads.post_id` = `posts.id` | |
INNER JOIN `comments` ON `comments.thread_id` = `threads.id`; | |
WHERE | |
`comments.user_id` = ? | |
How can I do this using the Eloquent query builder such that | |
when converted to JSON the results are properly nested. | |
Thee following is close: | |
$qry = Post | |
::with(['threads' => function ($query) use ($id) { | |
$query->with(['threadComments' => function ($query) use ($id) { | |
return $query->where('comment_id', $id); | |
}]); | |
}]) | |
->whereHas('threads', function ($query) use ($id) { | |
$query->whereHas('threadComments', function ($query) use ($id) { | |
$query->where('comment_id', $id); | |
}); | |
}) | |
->get(); | |
But this returns all threads (rather than just threads containing | |
comments by the user) for the posts. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment