【问题标题】:Laravel Eloquent query builder getting confused with 'or' operator in sqlLaravel Eloquent 查询构建器与 sql 中的“或”运算符混淆
【发布时间】:2016-09-02 06:09:40
【问题描述】:

如何为下面的 SQL 查询编写 laravel eloquent ? username、first_name、last_name 和 email 是列名。

 select * from `message_users` where `username` like %somthing% and (`first_name` like %somthing% or `last_name` like %somthing%) and `email` like %something%

我试过了

$queryObj= $this;
        if(!empty($filter['username']))
            $queryObj = $queryObj->where('username','like','%'.$filter['username'].'%');
        if(!empty($filter['name'])){
            $queryObj = $queryObj->where('first_name','like','%'.$filter['name'].'%');
            $queryObj = $queryObj->orWhere('last_nam','like','%'.$filter['name'].'%');
        }

        if(!empty($filter['email']))
            $queryObj = $queryObj->where('email','like','%'.$filter['email'].'%');

        $result = $queryObj->orderBy('id','DESC')->paginate($limit);
        return $result;

但这会构建没有圆括号的查询。哪个不给我正确的结果!

select * from `message_users` where `username` like %somthing% and `first_name` like %somthing% or `last_name` like %somthing% and `email` like %something%

【问题讨论】:

  • 不需要括号,它可以匹配or两侧的任何东西
  • 用单引号括起来的类似内容,如 '%something%'

标签: php sql laravel-5.2


【解决方案1】:

您可以使用 Advanced where clauses - parameter grouping 。闭包内的查询应包含在括号组中。

    if(!empty($filter['name'])){
        $queryObj->where(function ($query) use ($filter) {
            $query->where('first_name','like','%'.$filter['name'].'%')
                  ->orWhere('last_name','like','%'.$filter['name'].'%');
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2020-03-19
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多