php - Push an array into Laravel collection with matching keys -


i have collection called user, have array containing 2 models post relating user model.

the user collection contains primary key id , each model in post collection have foreign key user_id.

i executing following:

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

this works, not entirely because pulls in related posts instead of recent 2 posts user has made.


the array looks following:

enter image description here

my user schema looks like; hasmany relationship post:

enter image description here

you cannot use query constraints / eager loading this. doing work if retrieving posts 1 user. however, if try retrieve posts multiple users, fail because eager loading / query constraints limit related results whole. understand, have @ queries eloquent generates. lets take @ example need 1 user's posts.

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

in example, getting user primary key of 1. also retrieving his/her posts limiting retrieve 2 posts. works, , generate 2 queries similar this:

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

okay. now, why doesn't work if try more 1 user (or collection of users)? example:

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

in case, changed find(1) get(), , generate 2 queries this:

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

it's important take @ second query. it's retrieving related posts, @ end, you'll see has limit 2. in other words, it's limiting entire related collection 2, why query constraints not work this.

achieving pretty complex, fellow member (jarek tkaczyk) came solution using mysql variables, can find here: laravel - limit each child item efficiently


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -