【问题标题】:How to Create Multiple Where Clause Query Using Laravel Eloquent?如何使用 Laravel Eloquent 创建多个 Where 子句查询?
【发布时间】:2013-10-19 22:58:19
【问题描述】:

我正在使用 Laravel Eloquent 查询构建器,我有一个查询,我希望在多个条件下使用 WHERE 子句。它有效,但并不优雅。

例子:

$results = User::where('this', '=', 1)
    ->where('that', '=', 1)
    ->where('this_too', '=', 1)
    ->where('that_too', '=', 1)
    ->where('this_as_well', '=', 1)
    ->where('that_as_well', '=', 1)
    ->where('this_one_too', '=', 1)
    ->where('that_one_too', '=', 1)
    ->where('this_one_as_well', '=', 1)
    ->where('that_one_as_well', '=', 1)
    ->get();

有没有更好的方法来做到这一点,还是我应该坚持这种方法?

【问题讨论】:

  • 在如何简化这方面有很多可能性,但这需要一些更实际的代码。你能把代码更新得更真实一点吗?例如,有时多个->where(...) 调用可以替换为->whereIn(...) 调用,等等
  • @Jarek Tkaczyk 的解决方案应该是答案,我同意。但我更喜欢你的代码,比如生成器脚本,用于理解和维护。
  • 希望此链接对未来的用户有帮助
  • laravel 要求第一个调用是静态的,但其余的 -> 设计非常糟糕。
  • @paresh-mangukiya 请停止向旧问题添加虚假标签。他们没有帮助。

标签: php laravel eloquent laravel-query-builder


【解决方案1】:

查询范围可以帮助您提高代码的可读性。

http://laravel.com/docs/eloquent#query-scopes

用一些例子更新这个答案:

在你的模型中,像这样创建范围方法:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

然后,您可以在构建查询时调用此范围:

$users = User::active()->that()->get();

【讨论】:

  • 这样的条件的最佳实践是什么,query->where('start_date' > $startDate) 是否还可以使用 Scopes?
【解决方案2】:

您可以像这样在匿名函数中使用子查询:

 $results = User::where('this', '=', 1)
       ->where('that', '=', 1)
       ->where(
           function($query) {
             return $query
                    ->where('this_too', 'LIKE', '%fake%')
                    ->orWhere('that_too', '=', 1);
            })
            ->get();

【讨论】:

    【解决方案3】:

    Laravel 5.3 中(直到 7.x 仍然如此),您可以使用更精细的 wheres 作为数组传递:

    $query->where([
        ['column_1', '=', 'value_1'],
        ['column_2', '<>', 'value_2'],
        [COLUMN, OPERATOR, VALUE],
        ...
    ])
    

    就我个人而言,我还没有通过多次where 调用找到这个用例,但事实上你可以使用它。

    自 2014 年 6 月起,您可以将数组传递给 where

    只要你想让所有wheres使用and操作符,你可以这样分组:

    $matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
    
    // if you need another group of wheres as an alternative:
    $orThose = ['yet_another_field' => 'yet_another_value', ...];
    

    然后:

    $results = User::where($matchThese)->get();
    
    // with another group
    $results = User::where($matchThese)
        ->orWhere($orThose)
        ->get();
    

    以上将导致这样的查询:

    SELECT * FROM users
      WHERE (field = value AND another_field = another_value AND ...)
      OR (yet_another_field = yet_another_value AND ...)
    

    【讨论】:

    • 如何指定运算符?
    • @Styphon 你没有。目前它只适用于=
    • @Styphon 如果我想制作:WHERE (a IS NOT NULL AND b=1) OR (a IS NULL AND b=2);
    • 你也可以像这样传递一个条件数组:$users = DB::table('users')-&gt;where([ ['status', '=', '1'], ['subscribed', '&lt;&gt;', '1'], ])-&gt;get();
    • @jarek :如何根据您的回答将whereNotIn 包含在其他where 子句中?
    【解决方案4】:
    $variable = array('this' => 1,
                        'that' => 1
                        'that' => 1,
                        'this_too' => 1,
                        'that_too' => 1,
                        'this_as_well' => 1,
                        'that_as_well' => 1,
                        'this_one_too' => 1,
                        'that_one_too' => 1,
                        'this_one_as_well' => 1,
                        'that_one_as_well' => 1);
    
    foreach ($variable as $key => $value) {
        User::where($key, '=', $value);
    }
    

    【讨论】:

    • 这将执行多个查询。
    【解决方案5】:

    在这种情况下,您可以使用以下内容:

    User::where('this', '=', 1)
        ->whereNotNull('created_at')
        ->whereNotNull('updated_at')
        ->where(function($query){
            return $query
            ->whereNull('alias')
            ->orWhere('alias', '=', 'admin');
        });
    

    它应该为您提供如下查询:

    SELECT * FROM `user` 
    WHERE `user`.`this` = 1 
        AND `user`.`created_at` IS NOT NULL 
        AND `user`.`updated_at` IS NOT NULL 
        AND (`alias` IS NULL OR `alias` = 'admin')
    

    【讨论】:

      【解决方案6】:
      public function search()
      {
          if (isset($_GET) && !empty($_GET))
          {
              $prepareQuery = '';
              foreach ($_GET as $key => $data)
              {
                  if ($data)
                  {
                      $prepareQuery.=$key . ' = "' . $data . '" OR ';
                  }
              }
              $query = substr($prepareQuery, 0, -3);
              if ($query)
                  $model = Businesses::whereRaw($query)->get();
              else
                  $model = Businesses::get();
      
              return view('pages.search', compact('model', 'model'));
          }
      }
      

      【讨论】:

      • 这很容易受到 SQL 注入的攻击。
      【解决方案7】:

      确保对子查询应用任何其他过滤器,否则 or 可能会收集所有记录。

      $query = Activity::whereNotNull('id');
      $count = 0;
      foreach ($this->Reporter()->get() as $service) {
              $condition = ($count == 0) ? "where" : "orWhere";
              $query->$condition(function ($query) use ($service) {
                  $query->where('branch_id', '=', $service->branch_id)
                        ->where('activity_type_id', '=', $service->activity_type_id)
                        ->whereBetween('activity_date_time', [$this->start_date, $this->end_date]);
              });
          $count++;
      }
      return $query->get();
      

      【讨论】:

        【解决方案8】:

        多个 where 子句

            $query=DB::table('users')
                ->whereRaw("users.id BETWEEN 1003 AND 1004")
                ->whereNotIn('users.id', [1005,1006,1007])
                ->whereIn('users.id',  [1008,1009,1010]);
            $query->where(function($query2) use ($value)
            {
                $query2->where('user_type', 2)
                    ->orWhere('value', $value);
            });
        
           if ($user == 'admin'){
                $query->where('users.user_name', $user);
            }
        

        终于得到结果了

            $result = $query->get();
        

        【讨论】:

          【解决方案9】:

          您可以在 Laravel 5.3

          中使用 eloquent

          所有结果

          UserModel::where('id_user', $id_user)
                          ->where('estado', 1)
                          ->get();
          

          部分结果

          UserModel::where('id_user', $id_user)
                              ->where('estado', 1)
                              ->pluck('id_rol');
          

          【讨论】:

          • 这与问题有何不同?
          【解决方案10】:

          whereColumn 方法可以传递多个条件的数组。这些条件将使用and 运算符连接。

          示例:

          $users = DB::table('users')
                      ->whereColumn([
                          ['first_name', '=', 'last_name'],
                          ['updated_at', '>', 'created_at']
                      ])->get();
          
          $users = User::whereColumn([
                          ['first_name', '=', 'last_name'],
                          ['updated_at', '>', 'created_at']
                      ])->get();
          

          有关更多信息,请查看文档的此部分 https://laravel.com/docs/5.4/queries#where-clauses

          【讨论】:

            【解决方案11】:

            使用数组的条件:

            $users = User::where([
                   'column1' => value1,
                   'column2' => value2,
                   'column3' => value3
            ])->get();
            

            将产生如下查询:

            SELECT * FROM TABLE WHERE column1 = value1 and column2 = value2 and column3 = value3
            

            使用匿名函数的条件:

            $users = User::where('column1', '=', value1)
                           ->where(function($query) use ($variable1,$variable2){
                                $query->where('column2','=',$variable1)
                               ->orWhere('column3','=',$variable2);
                           })
                          ->where(function($query2) use ($variable1,$variable2){
                                $query2->where('column4','=',$variable1)
                               ->where('column5','=',$variable2);
                          })->get();
            

            将产生如下查询:

            SELECT * FROM TABLE WHERE column1 = value1 and (column2 = value2 or column3 = value3) and (column4 = value4 and column5 = value5)
            

            【讨论】:

              【解决方案12】:

              使用whereIn 条件并传递数组

              $array = [1008,1009,1010];

              User::whereIn('users.id', $array)-&gt;get();

              【讨论】:

                【解决方案13】:
                $projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
                    ['status','<>','Pending'],
                    ['status','<>','Not Available']])
                ->orwhere([['owner', 'like', '%'.$input.'%'],
                    ['status','<>','Pending'],
                    ['status','<>','Not Available']])->get();
                

                【讨论】:

                  【解决方案14】:

                  你可以在where子句中使用数组,如下所示。

                  $result=DB::table('users')->where(array(
                  'column1' => value1,
                  'column2' => value2,
                  'column3' => value3))
                  ->get();
                  

                  【讨论】:

                    【解决方案15】:
                    Model::where('column_1','=','value_1')
                           ->where('column_2 ','=','value_2')
                           ->get();
                    

                    // If you are looking for equal value then no need to add =
                    Model::where('column_1','value_1')
                            ->where('column_2','value_2')
                             ->get();
                    

                    Model::where(['column_1' => 'value_1',
                                  'column_2' => 'value_2'])->get();
                    

                    【讨论】:

                    • 好东西.. 谢谢@DsRaj
                    【解决方案16】:
                    DB::table('users')
                                ->where('name', '=', 'John')
                                ->orWhere(function ($query) {
                                    $query->where('votes', '>', 100)
                                          ->where('title', '<>', 'Admin');
                                })
                                ->get();
                    

                    【讨论】:

                      【解决方案17】:

                      根据我的建议,如果您正在过滤或搜索

                      那么你应该选择:

                              $results = User::query();
                              $results->when($request->that, function ($q) use ($request) {
                                  $q->where('that', $request->that);
                              });
                              $results->when($request->this, function ($q) use ($request) {
                                  $q->where('this', $request->that);
                              });
                              $results->when($request->this_too, function ($q) use ($request) {
                                  $q->where('this_too', $request->that);
                              });
                              $results->get();
                      

                      【讨论】:

                      • 搜索是发生在phpside还是sql端?
                      • Sql 端。 Sql 查询作为请求参数执行。前任。如果requrst 有这个参数。然后 where this = '' where 条件添加到查询中。
                      【解决方案18】:

                      使用这个

                      $users = DB::table('users')
                                          ->where('votes', '>', 100)
                                          ->orWhere('name', 'John')
                                          ->get();
                      

                      【讨论】:

                        【解决方案19】:

                        使用纯 Eloquent,像这样实现它。此代码返回其帐户处于活动状态的所有登录用户。 $users = \App\User::where('status', 'active')-&gt;where('logged_in', true)-&gt;get();

                        【讨论】:

                          【解决方案20】:

                          代码示例。

                          首先:

                          $matchesLcl=[];
                          

                          数组在此处使用 条件的所需计数/循环填充,增量:

                           $matchesLcl['pos']= $request->pos;
                          $matchesLcl['operation']= $operation;
                          //+......+
                          $matchesLcl['somethingN']= $valueN;
                          

                          还有像这种收缩表达这样的雄辩:

                          if (!empty($matchesLcl))
                              $setLcl= MyModel::select(['a', 'b', 'c', 'd'])
                                  ->where($matchesLcl)
                                  ->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));
                          else 
                              $setLcl= MyModel::select(['a', 'b', 'c', 'd'])
                                  ->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));
                          

                          【讨论】:

                            【解决方案21】:

                            如果你的条件是这样的(匹配单个值),一个更简单更优雅的方法是:

                            $results = User::where([
                                     'this' => value,
                                     'that' => value,
                                     'this_too' => value,
                                      ...
                                  ])
                                ->get();
                            

                            但如果您需要 OR 子句,请确保为每个 orWhere() 子句重复必须满足条件。

                                $player = Player::where([
                                        'name' => $name,
                                        'team_id' => $team_id
                                    ])
                                    ->orWhere([
                                        ['nickname', $nickname],
                                        ['team_id', $team_id]
                                    ])
                            

                            【讨论】:

                              【解决方案22】:

                              使用 Eloquent 可以轻松创建多个 where 检查:

                              首先:(使用简单的where)

                              $users = User::where('name', $request['name'])
                                  ->where('surname', $request['surname'])
                                  ->where('address', $request['address'])
                                  ...
                                  ->get();
                              

                              第二:(将你的 where 分组到一个数组中)

                              $users = User::where([
                                  ['name', $request['name']],
                                  ['surname', $request['surname']],
                                  ['address', $request['address']],
                                  ...
                              ])->get();
                              

                              您也可以在其中使用条件(=、 等),如下所示:

                              $users = User::where('name', '=', $request['name'])
                                  ->where('surname', '=', $request['surname'])
                                  ->where('address', '<>', $request['address'])
                                  ...
                                  ->get();
                              

                              【讨论】:

                                【解决方案23】:

                                我们使用该指令根据用户分类类型和用户名两个条件获取用户。

                                除了从配置文件表中获取用户信息以减少查询次数之外,我们还使用两个条件在您键入时进行过滤。

                                $users = $this->user->where([
                                                    ['name','LIKE','%'.$request->name.'%'],
                                                    ['trainers_id','=',$request->trainers_id]
                                                    ])->with('profiles')->paginate(10);
                                

                                【讨论】:

                                  【解决方案24】:

                                  您可以通过多种方式使用,

                                  $results = User::where([
                                      ['column_name1', '=', $value1],
                                      ['column_name2', '<', $value2],
                                      ['column_name3', '>', $value3]
                                  ])->get();
                                  

                                  你也可以这样使用,

                                  $results = User::orderBy('id','DESC');
                                  $results = $results->where('column1','=', $value1);
                                  $results = $results->where('column2','<',  $value2);
                                  $results = $results->where('column3','>',  $value3);
                                  $results = $results->get();
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    你可以这样做,这是最短的方法。

                                        $results = User::where(['this'=>1, 
                                                  'that'=>1, 
                                                   'this_too'=>1, 
                                                   'that_too'=>1, 
                                                  'this_as_well'=>1, 
                                                   'that_as_well'=>1, 
                                                    'this_one_too'=>1, 
                                                   'that_one_too'=>1, 
                                                  'this_one_as_well'=>1,
                                                    'that_one_as_well'=>1])->get();
                                    

                                    【讨论】:

                                      【解决方案26】:

                                      在 Eloquent 中你可以试试这个:

                                      $results = User::where('this', '=', 1)
                                      ->orWhere('that', '=', 1)
                                      ->orWhere('this_too', '=', 1)
                                      ->orWhere('that_too', '=', 1)
                                      ->orWhere('this_as_well', '=', 1)
                                      ->orWhere('that_as_well', '=', 1)
                                      ->orWhere('this_one_too', '=', 1)
                                      ->orWhere('that_one_too', '=', 1)
                                      ->orWhere('this_one_as_well', '=', 1)
                                      ->orWhere('that_one_as_well', '=', 1)
                                      ->get();
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2015-01-19
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2015-06-03
                                        相关资源
                                        最近更新 更多