Ad

Push An Array Into Laravel Collection With Matching Keys

- 1 answer

I have a collection called User, I also have an array containing two models Post relating to the User model.

The User collection contains a primary key id and each model in my Post collection I have a foreign key user_id.

I am currently executing the following:

foreach ($users as $user) {
    foreach ($posts as $post) {
        if ($post->user_id == $user->id) {
            $user->posts->push($post);
        }
    }
}

This somewhat works, but not entirely because it pulls in all related posts instead of the recent two posts a user has made.


The array looks like the following:

enter image description here

My User schema looks like; with a hasMany relationship to Post:

enter image description here

Ad

Answer

You cannot use query constraints / eager loading to do this. Doing so will only work if you are retrieving the posts for one user. However, if you try to retrieve the posts for multiple users, it will fail because eager loading / query constraints will limit the related results as a whole. To understand, you have to look at the queries Eloquent generates. Lets take a look at an example where you only need one user's posts.

$user = User::with(['posts' => function($query) {
    $query->limit(2);
}])->find(1);

In this example, we are getting a user with a primary key of 1. We also also retrieving his/her posts but limiting it so we only retrieve 2 posts. This works, and it will generate 2 queries similar to this:

select * from `users` where `users`.`id` = 1 limit 1
select * from `posts` where `posts`.`user_id` in (1) limit 2

Okay. Now, why doesn't this work if you try to get more than 1 user (or a collection of users)? For example:

$user = User::with(['posts' => function($query) {
    $query->limit(2);
}])->get();

In this case, I changed find(1) to get(), and it will generate 2 queries like this:

select * from `users`
select * from `posts` where `posts`.`user_id` in (?, ?, ?, ... ?) limit 2

It's important to take a look at the second query. It's retrieving all the related posts, but at the end, you'll see that it has limit 2. In other words, it's limiting the entire related collection to only 2, which is why query constraints do not work for this.

Achieving this is actually pretty complex, but a fellow member (Jarek Tkaczyk) came up with a solution using MySQL variables, which you can find here: Laravel - Limit each child item efficiently

Ad
source: stackoverflow.com
Ad