繁体   English   中英

Laravel模型使用或在什么条件下使用?

[英]Laravel Model Using Or in where Condition?

我想从数据库中的user_webhook表中获取模板。在什么情况下,我正在检查user_id,app_id以及user_webhook表中的notify_admin或notify_customer值是否为1。我正在使用查询。

$templates= $this->where('notify_admin',1)
                 ->orwhere('notify_customer',1)
                 ->where('user_webhooks.user_id',$user_id)
                 ->where('user_webhooks.app_id',$app_id)
                 ->select(  'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
                            'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
                            'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
                            'user_webhooks.sms_template as sms'
                         )
                 ->join ('webhooks',function($join){
                      $join>on('webhooks.id','=','user_webhooks.webhook_id');
                        })
                 ->get()
                 ->toArray();

当我使用DB :: getQueryLog()获取查询时,我发现查询看起来像

select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
 `telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
 `telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
 `telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`, 
 `telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`, 
 `telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks` 

 inner join  
 `telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id` 

  where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id` 
  = ? and  `telhok_user_webhooks`.`app_id` = ?

查询结果给出所有app_id和user_id的结果。 因此,请告诉我在何处使用OR。 提前致谢。

您可以将约束链接在一起,也可以在查询中添加或子句。 orWhere方法接受与where方法相同的参数:

$users = DB::table('users')
                ->where('votes', '>', 100)
                ->orWhere('name', 'John')
                ->get();

高级用法:

Usere::where('id', 46)
      ->where('id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

whereIn方法验证给定数组中是否包含给定列的值:

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();

更多: https//laravel.com/docs/5.5/queries

更改

->where('notify_admin',1)
->orwhere('notify_customer',1)

->where(function($q){
  $q->where('notify_admin',1)
  ->orWhere('notify_customer',1);
})

否则,orWhere将与查询中的所有其他位置进行比较,而不仅仅是比较这两列

暂无
暂无

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

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