【问题标题】:Laravel query builder with AND in query在查询中使用 AND 的 Laravel 查询构建器
【发布时间】:2013-02-23 12:27:37
【问题描述】:

我想在查询生成器的末尾添加一个“AND”子句,代码如下所示:

$orderers = DB::table('address')->where(function($query) use ($term) {
                            $query->where('id', 'LIKE', '%' . $term . '%')
                                    ->or_where('name', 'LIKE', '%' . $term . '%')
                                    ->or_where('status', 'LIKE', '%' . $term . '%')
                                    ->and_clause_goes_here('is_orderer', '=', '1');
                        })->paginate($per_page);

但是在 Laravel 中搜索 AND 子句时,我找不到任何等价物。你能帮我解决这个问题吗?

【问题讨论】:

    标签: php laravel-3


    【解决方案1】:

    只需另一个 where 子句即可,使用 AND

    $orderers = DB::table('address')->where(function($query) use ($term) {
                                $query->where('id', 'LIKE', '%' . $term . '%')
                                        ->where('is_orderer', '=', '1');
                                        ->or_where('name', 'LIKE', '%' . $term . '%')
                                        ->or_where('status', 'LIKE', '%' . $term . '%')
                            })->paginate($per_page);
    

    【讨论】:

      【解决方案2】:

      由于操作的顺序,JCS 解决方案可能仍会产生一些意想不到的结果。您应该像在 SQL 中那样将所有 OR 组合在一起,明确定义逻辑。它还使您(或其他团队成员)下次阅读代码时更容易理解。

      SELECT * FROM foo WHERE a = 'a' 
      AND (
          WHERE b = 'b'
          OR WHERE c = 'c'
      )
      AND WHERE d = 'd'
      
      
      Foo::where( 'a', '=', 'a' )
          ->where( function ( $query )
          {
              $query->where( 'b', '=', 'b' )
                  ->or_where( 'c', '=', 'c' );
          })
          ->where( 'd', '=', 'd' )
          ->get();
      

      【讨论】:

      • 老兄,正是我要找的东西
      • 非常感谢。我认为它必须是orWhere 而不是or_where。它在 laravel 5.5 中导致错误。
      猜你喜欢
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2017-06-29
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多