douhuantui6259 2018-03-13 05:58 采纳率: 100%
浏览 615
已采纳

求助:在WHERE中使用OR子句或在eloquent的laravel中使用HAVING

我正在为构建RESTAPI开发一个Laravel项目。我正在使用eloquent从数据库中Fatch数据。如果只有一个WHERE和一个WHERE条件,它没有问题,但在这里我使用多个WHERE子句。比如,如果我们编写核心MySQL查询,我们可以这样写:

SELECT * FROM table_name WHERE uid = 1 
AND (id = 1 AND name = test1) OR (id = 2 AND name = test2);

但是当我们使用eloquent,以及在模型中使用 orWhere 时,我们需要这样做:

Model::select('*')->where('uid', '1')
->where('id', '1')
->where('name', 'test1')
->orWhere('uid', '1')
->where('id', '1')
->where('name', 'test1')
->get();

有时,当我尝试制作任何可以根据表的参数数搜索数据的搜索API时,我需要多次编写相同的代码。

  • 写回答

3条回答 默认 最新

  • dongshi9526 2018-03-13 07:24
    关注

    The equivalent in eloquent of parenthesis would be using a closure as the parameter of where or orWhere

    (a or b) and (c or d) would be:

    ->where(function($q){
      $q->where(a)->orWhere(b);
    })->where(function($q){
      $q->where(c)->orWhere(d);
    });
    

    and

    (a and b) or (c and d) would be:

    ->where(function($q){
      $q->where(a)->where(b);
    })->orWhere(function($q){
      $q->where(c)->where(d);
    });
    

    but

    a or b and c or d would be:

    ->where(a)->orWhere(b)->where(c)->orWhere(d)
    

    which is something completely different.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?