Nested relationships stop working after the first result

Here is the query I have:

$messages = Message::select('messages.*') ->where('post_id', 1) ->where('parent_id', 0) ->with(['children' => function ($query) { $query->take(3); }]) ->paginate(10); 

And here is the children link in my Message.php class:

 public function children() { return $this->hasMany('App\Message', 'parent_id', 'id'); } 

This is the result I'm trying to get:

 - Message 1 - Message 1.1 - Message 1.2 - Message 1.3 - Message 2 - Message 2.1 - Message 2.2 - Message 2.3 - Message 3 - Message 3.1 - Message 3.2 - Message 3.3 - etc 

But instead, it returns this:

 - Message 1 - Message 1.1 - Message 1.2 - Message 1.3 - Message 2 - Message 3 - etc 

The query seems to return only for the first result, but another result after.

What am I doing wrong? How can I correct my query to get the desired results?

+5
source share
1 answer

Firstly, to answer the question β€œWhat am I doing wrong?”, If you follow the documentation for intensive downloaded downloads, let's see that the request you created is translated as follows:

 select * from messages select * from children where id in (1, 2, 3, 4, 5, ...) limit 3 

(Note that I compiled the name of the children table, since I do not know which name you are using.)

After retrieving the records, Eloquent will build its object using exactly what you requested: all messages and all their children - limited to three lines . That is why you only get children for the first Message .


Now, if you want to stick to active loading, you can just get rid of the closure in the with method:

 $messages = Message::select('messages.*') ->where('post_id', 1) ->where('parent_id', 0) ->with('children') /* the constraint is gone */ ->paginate(10); 

Using this paginated result, you will have access to all Messages and all your relevant children. Then, for example, in the controller, you can change your result by filtering it out or manually restricting each group of children to 3. Or you do it quickly and dirty and use the loop with break right in your view.

But do not do it quickly and dirty.

+1
source

Source: https://habr.com/ru/post/1268753/


All Articles