Where Condition on relationship in Laravel

Viewed 70

I am trying to fetch users based on their role_id from database through ajax. I did this using below code.

        $queryModel->whereHas('roles',function ($query) use ($role_id) {
           $query->where("role_id",$role_id);
        });

But on live server I have more than 40,000 users so it takes a lot of time to fetch data. This is because of using whereHas().I tried using where but it did not work. is there any solution which makes search fast.

1 Answers

If you have a Role model which also have a relation with User model you can try something like this;

$role = Role::findOrFail($role_id);
$users = $role->users; // got all users which have that specific role
// or you can use query builder
$users = $role->users()->where('name', 'like', 'U%')->get();

As a result you don't need to check all users to find which of them have a specific role. You start with role and access it's users.

Related