前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Laravel orWhere条件

Laravel orWhere条件

作者头像
句小芒
发布2022-12-29 18:05:39
3230
发布2022-12-29 18:05:39
举报
场景描述

需要根据三个条件去查询结果集,三个条件的关系是A and (B or C),B条件和C条件有交集,需要取出他两的并集。 如果用户登录(UID存在),条件为A and (B or C),用户未登录,查询条件为:A and B

错误代码1
代码语言:javascript
复制
$uid = $params['uid']??0;
$comment = DB::table('users')->where('A', '=', "2")
$comment  = $comment->when($uid>0, function ($query) use ($uid) {
      $comment->where('B', '=', "1")->orWhere('uid','=',$uid);
  }, function ($query) {
      $comment->where('B', '=', "1")
  })
      ->get();

错误代码2
代码语言:javascript
复制
$uid = $params['uid']??0;
$comment = DB::table('users')->where('A', '=', "2")
if ($uid>0) {
    $comment  = $goodsModel->where('B', '=', "1")->orWhere('uid', '=', "$uid")->get();
}else{
	$comment  = $goodsModel->where('B', '=', "1")->get();
}
这样的写法会导致三者的关系变成了:A and B or C

正确代码
代码语言:javascript
复制
$uid = $params['uid']??0;
$comment = DB::table('users')->where('A', '=', "2")
if ($uid>0) {
    $comment = $comment ->where(function ($query) use ($uid) {
        $query->where('B', '=', "1")->orWhere('uid', '=', "$uid");
    });
}else{
    $commentInfo = $query->where(function ($query) use ($uid) {
        $query->where('B', '=', "1");
    });
}
正确的关系 A and (B or C)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 场景描述
    • 错误代码1
      • 错误代码2
        • 这样的写法会导致三者的关系变成了:A and B or C
      • 正确代码
        • 正确的关系 A and (B or C)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档