How to use orWhere in whereHas in Laravel

I have three tables user, role, permission, userhasMany role, rolehasMany permission, I want to know who has a permit, which I gave, so I usewhereHas

$user = User::whereHas('roles', function($q) {
    $q->whereHas('permissions', $function($q) {
        $q->where('name', $value);
    });
});

The result is correct, but if I want to search for a user according to more conditions, I give a different permission value and use it orWhere, it answers all users who have any permissions, how to fix it?

$user = User::whereHas('roles', function($q) {
    $q->whereHas('permissions', $function($q) {
        $q->where('name', $value)->orWhere('name', $value2);
    });
});
+4
source share
2 answers

Avoid using the $ q variable in the first where it should work

User::has('roles')->whereHas('permissions', $function($q) {
        $q->where('name', $value)->orWhere('name', $value2);
    });
+1
source

: . , . :

Company::where('name', 'like', '%'.$searchstring.'%')
         ->orWhereHas('contacts', function($q) use ($searchstring) { 
                                    $q->where('forename', 'like', '%'.$searchstring.'%')
                                    ->orWhere('lastname', 'like', '%'.$searchstring.'%');
                                   });

, : .

, , , - . :

Company::with('mainContact', 'contacts')
         ->where('name', 'like', '%'.$searchstring.'%')
         ->orWhereHas('contacts', function($q) use ($searchstring) { 
                                    $q->where('forename', 'like', '%'.$searchstring.'%');
                                  })
         ->orWhereHas('contacts', function($q) use ($searchstring) { 
                                    $q->where('lastname', 'like', '%'.$searchstring.'%');
                                  });

, SQL-, . .

+1

Source: https://habr.com/ru/post/1528061/


All Articles