I
I
Ivan2019-02-11 23:28:28
Laravel
Ivan, 2019-02-11 23:28:28

How to make a selection whereIn + with with a limit on each record?

There are 2 tables:
users and posts
need to make a whereIn selection in users

public static function users(){

return self::whereIn('login', ['ivanov', 'petrov' ])->get();

}

the relationship between users and posts works through a relationship
public function posts(){

return $this ->hasMany(Posts::class );

}

the final build is:
public static function users(){

return self::whereIn('login', ['ivanov', 'petrov' ])->with(['posts' => function($query){

return $query -> take(5);

}])->get();

}

those. I want to get 5 posts for each user, but orm returns 5 posts for 2 users in total.
Question: how can you implement such a task and not govnokodit?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jazzus, 2019-02-12
@jazzus

You can try with osprey in the User model

public function scopeOfLogins($query, $logins)
{
         $builder = $query->whereIn('login', $logins)
                         ->with(['posts' => function($q){
                                      $q->take(5);
                                     }]);
    return $builder;
}

in controller
$logins = ['ivanov', 'petrov'];
$users = User::ofLogins($login)->get();

or with a forych in the user
public function scopeOfLogins($query, $logins)
{
    foreach ($logins as $login) {
         $builder = $query->where('login', $login)
                           ->with(['posts' => function($q){
                           $q->take(5);
                           }]);
    }
    return $builder;
}

V
vism, 2019-02-12
@vism

Here's how it happens, 2 solutions and in both people don't know how eager loading works... :)
Here's a normal solution for you.
To take the last 5 for each entry, you need to make a separate request for each User. this is how the database works, otherwise a very complex query is obtained like this.

$articles = `SELECT category, id, title FROM (
    SELECT c.name AS category, a.id, a.title, row_number() OVER (PARTITION BY categoryid ORDER BY a.sort DESC) AS row
    FROM articles a INNER JOIN categories c ON (a.categoryid=c.dboid)
    ORDER BY c.sort
) AS foo WHERE row <= 5;

Therefore, first you get users, and then go through them in a loop and get everything related to posts
foreach ($users as $user) {
         user->load(['posts' => function($q){
                           $q->take(5);
                           }]);
    }

N
NubasLol, 2019-02-12
@NubasLol

Use package
https://github.com/staudenmeir/eloquent-eager-limi...
By default, take in with does not work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question