Skip to content

Instantly share code, notes, and snippets.

@euoia
Last active December 4, 2018 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euoia/2b64b4fc77e6c448d6f1a7dffea8874a to your computer and use it in GitHub Desktop.
Save euoia/2b64b4fc77e6c448d6f1a7dffea8874a to your computer and use it in GitHub Desktop.
# 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