Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-many then eager load an array with Laravel Eloquent ORM

With Laravel and the eloquent ORM, I want to create an array or object of all posts and corresponding comments that belong to a specific user (the logged in one). The result will then be used with Response::eloquent(); to return JSON.

Basically in pseudo-code:

All Posts by user ::with('comments').

or

Posts by Auth::user()->id ::with('comments').

I have my database setup per the usual with a user's table, comments table and posts table. The comments table has a post_id and the posts table has a user_id.

The long way of doing this without Laravel would be something like:

SELECT * FROM posts WHERE user_id = 'user_id'
foreach($result as $post) {
    SELECT * FROM comments WHERE posts_id =  $post->id
    foreach($query as $comment) {
        $result[$i]->comments[$n] = $comment
    }
}

But I want to accomplish it with Laravel's Eloquent ORM.

like image 840
drew schmaltz Avatar asked Jan 11 '13 23:01

drew schmaltz


1 Answers

It looks like you don't even need a nested eager load, you just need to modify the query that with returns, so:

$posts = Post::with('comments')->where('user_id', '=', 1)->get();

You can daisy chain most of the methods in the Eloquent system, generally they're just returning a Fluent query object.

(I haven't tested it but I'm fairly certain that'll work. Also, you can't do it on ::all() because that calls ->get() for you. You have to dig in the source code to find this, I don't think the Eloquent documentation mentions that's what it's doing.)

Also the Eager Loading Documentation covers nested eager loading, so you could load all users, with their posts, with the comments:

You may even eager load nested relationships. For example, let's assume our Author model has a "contacts" relationship. We can eager load both of the relationships from our Book model like so:

$books = Book::with(array('author', 'author.contacts'))->get();
like image 153
Cthos Avatar answered Nov 18 '22 14:11

Cthos