lundi 19 novembre 2018

Laravel Eloquent join vs with

I see that join is (by default inner join) and its returning all columns but it takes almost the same time as with keyword for just 1000 data.

$user->join(‘profiles’, ‘users.id’, ‘=’, ‘profiles.user_id’) - generates the below query.

select * from `users` inner join `profiles` on `users`.`id` = `profiles`.`user_id` where `first_name` LIKE '%a%'`

User::with(‘profile’) - this eager loading outputs the below query

select * from `users` where exists (select * from `profiles` where `users`.`id` = `profiles`.`user_id` and `first_name` LIKE '%a%')

which is the best way to return a list of users with a pagination for a REST API ? eager loading seems promising but its with a sub query.

if do with eager loading, this is how i will be filtering. need to use whereHas

if($request->filled('first_name')){
        $query->whereHas('profile',function($q) use ($request){
            $q->where('first_name','like','%'.request('first_name').'%');
        });
    }

but if used Join, its less lines of code.

  if ($request->filled('first_name')) {
            $users = $users->where('first_name', 'LIKE', "%$request->first_name%");
        }

laravel version is 5.7



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire