Answer the question
In order to leave comments, you need to log in
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();
}
public function posts(){
return $this ->hasMany(Posts::class );
}
public static function users(){
return self::whereIn('login', ['ivanov', 'petrov' ])->with(['posts' => function($query){
return $query -> take(5);
}])->get();
}
Answer the question
In order to leave comments, you need to log in
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;
}
$logins = ['ivanov', 'petrov'];
$users = User::ofLogins($login)->get();
public function scopeOfLogins($query, $logins)
{
foreach ($logins as $login) {
$builder = $query->where('login', $login)
->with(['posts' => function($q){
$q->take(5);
}]);
}
return $builder;
}
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;
foreach ($users as $user) {
user->load(['posts' => function($q){
$q->take(5);
}]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question