Search code examples
phpmysqllaravellaravel-5eloquent

How to limit the count of rows for a specific foreign key value in Laravel


We have a posts table and user_id is the foreign key For example, I want to choose posts for these users

$users=[1,2,13,16,17,19];
$posts = Post::whereIn('user_id', $users)->paginate(10);

But I want the user 1 and 2 only have two posts in the output, for the rest of the users there is not a limited number of posts.

Note: User 1 and 2 are not always within the $users array, and due to the condition, one or both of them may not be in the array.

Do you have a solution for me?


Solution

  • You can try this alternative :

    $posts = [];
    $users=[1,2,13,16,17,19];
    $userWithJustTwo = [1,2];
    $result = array_intersect($users, $userWithJustTwo); 
    $posts[] = Post::whereIn('user_id', $result)->orderBy('created_at', 'desc')->take(2)->get();
    $array = array_diff($users, userWithJustTwo);
    $posts[] = Post::whereIn('user_id', $array)->get();