简体   繁体   English

在where子句中检查或条件

[英]check or condition in where clause

I want to check OR condition for the variable role_id in role_mapping table. 我要检查role_mapping表中变量role_id的 OR条件。 I want to check if user_id has role_id either '2' or '3'. 我想检查user_id是否具有role_id为'2'或'3'。 User with user_id=210 has role_id 2 and 1. but my query result prints '3'. user_id = 210的用户具有role_id 2和1。但是我的查询结果显示为'3'。 How to use or condition in Laravel query? 如何在Laravel查询中使用或调节条件?

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

AND operator has higher priority than OR operator, so the query you're running is: AND运算符的优先级高于OR运算符,因此您正在运行的查询为:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM