user3386779
user3386779

Reputation: 7175

check or condition in where clause

I want to check OR condition for the variable role_id in role_mapping table. I want to check if user_id has role_id either '2' or '3'. User with user_id=210 has role_id 2 and 1. but my query result prints '3'. How to use or condition in Laravel query?

Role table
  user_id role_id 
   210     2
   210     1

    $user_role=role_mapping::where('user_id','=',210)
    ->where('role_id','=','2')
    ->orwhere('role_id','=','3')
    ->select('role_mapping.role_id')->first();

     echo $user_role->role_id;  // print 3

Upvotes: 2

Views: 732

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

AND operator has higher priority than OR operator, so the query you're running is:

WHERE (user_id = 210 AND role_id = 2) OR role_id = 3

while you should be running

WHERE user_id = 210 AND (role_id = 2 OR role_id = 3)

The following will do the trick:

role_mapping::where('user_id','=',210)
  ->where(function($query) {
    $query->where('role_id','=','2')->orWhere('role_id','=','3');
  })
  ->select('role_mapping.role_id')->first();

Upvotes: 6

Related Questions