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 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据