0

When I eager-load the relations via eloquent methods, some records have empty relations. I can filter the records simply by using Collection's filter method. How can I filter those records while querying?

I have multiple users and each user can have have multiple roles (Admin, Employee, User). In a scenario, I want to list out all the users that have Employee roles. I eager-loaded the roles (constrained to employee) for users. But the users with no employee role also were there in resultant data.

So I have to either filter out this data using collection's collect method, or skip eager-loading and use "querying relationship". But then this could be time-consuming if roles, users increase in number in database.

//filtering out in collection
$employees = User::with(['roles'=> function($query){
                 $query->where('name', 'Employee');
             }])->get()->filter(function($value, $key){
                 return $value->roles->count() > 0;
             });

//querying relationship
$employees = User::whereHas('roles', function($query){
                 $query->where('name', 'Employee');
             })->get();

I also tried to use 'with' and 'whereHas' together. But using the same on a different large dataset consumed a lot of time than using just 'with'. So I just dropped this option.

So, is there any way that I can fetch only users having role employees while having used 'with'?

  • AFAIK if you want to use Eloquent you need to [use `has`](https://stackoverflow.com/questions/31598949/laravel-eloquent-select-only-rows-where-the-relation-exists) or [`whereHas`](https://stackoverflow.com/questions/45355201/get-object-only-when-relation-result-is-exist-laravel), though performance might not be great. Alternatively you could use `DB` and query builder to write something more efficient. – Don't Panic Apr 22 '19 at 12:31
  • thanks @Don'tPanic. In my case, has or whereHas were efficient for smaller dataset. So I chose another way, rather eager-loading roles for user, I eager-loaded users for a role. I had to make adjustments in other parts of code, but yes, it achieved the answer. – Kalpashree V. Bal May 03 '19 at 06:33

0 Answers0