Search code examples
laravellaravel-5eloquentlaravel-collection

Laravel: Query on the same table multiple times


I have a table of users

+-------+------+-----+
| User  | Sale | Sex |
+-------+------+-----+
| user1 |  120 | M   |
| user2 |   98 | M   |
| user3 |    5 | F   |
+-------+------+-----+

in laravel, we query this by the following statement:

$allMale = UserTable::where('Sex', 'M')->get();

What will happen in I try to query again on the same table

 $allFemales = UserTable::where('Sex', 'F')->get();
 $user1 = UserTable::where('User', 'user1')->get();

will it query 3 times? is it possible to query once and then Parse it multiple times?


Solution

  • Yes, I'm not sure if UserTable here is Builder or Eloquent but Eloquet under the hood is using MySQL so it will run 3 different queries:

    SELECT * FROM users WHERE Sex = 'M';
    SELECT * FROM users WHERE Sex = 'F';
    SELECT * FROM users WHERE User = 'user1';
    

    Of course you can do it like this:

    $users = UserTable::where(function($q) {
      $q->whereIn('Sex', ['M', 'F'])->orWhere('User', 'user1')
    })->get();
    

    This will generate query:

    SELECT * FROM users WHERE ((Sex IN ('M', 'F') OR USER = 'user1'))
    

    and now you can get those users from variable like this using Laravel collection methods:

    $allMale = $users->where('Sex', 'M')->get();
    $allFemales = $users->where('Sex', 'F')->get();
    $user1 = $users->where('User', 'user1')->get();
    

    Now, assuming that user1 has sex set, you could in fact use:

    $users = UserTable::whereIn('Sex', ['M', 'F'])->get();
    

    In addition, assuming there is only single user1 instead of:

    $user1 = $users->where('User', 'user1')->get();
    

    probably better solution would be:

    $user1 = $users->where('User', 'user1')->first();