【问题标题】:Laravel: dynamic where clause with ElouquentLaravel:带有 Elouquent 的动态 where 子句
【发布时间】:2015-09-05 16:44:03
【问题描述】:

我正在使用动态搜索参数调用 URL。我怎样才能形成正确的 Eloquent 查询

理论上:

  1. 查询
  2. 查询 where(someParam1)
  3. 查询 where(someParam2)
  4. 查询 orderby(someParam3)
  5. 查询获取

我需要这种结构,所以如果 param 存在,我可以使用 where 子句。 如果 Laravel 有其他方法,请告诉我。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以将回调传递给 where 函数。

    所以,你可以这样做:

    class TestService {
    
       TestRepository $testeRepository;
    
       public function __construct(TesteRepository $teste) {
          $this->testeRepository = $teste;
       }
    
       public function getAll(array $filters)
       {
          $where = function (Builder $query) use ($filters) {
             collect($filters)
                ->each(function ($value, $param) use ($query) {
                   if ($param === 'test') {
                      $query->where($param, '=', $value); 
                   } else if ($param === 'test2') {
                      $query->orWhere($param, '>', $value);
                   }
                });
          };
          return $this->testRepository->gelAll($where);
       }
    
    class TestRepository
    {
       public function getAll(\Closure $where)
       {
            $query = TestModel::query();
            $query->where($where);
            //and put more stuff here, like:
            //$query->limit(15)->offset(30)
            ...
           return $query->get();
       }
    }
    

    然后在您的控制器中传递过滤器:

    class TestControler ...
    {
        public function $index()
        {
           $filters = request()->query();
           return $this->testService->getAll($filters);
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以只使用 where 语句。 例如:在users 表或User 模型上,您需要动态搜索名称、id。你可以这样做

      $where = [];
      $firstName = $request->get('first_name');
      if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
      $id = $request->get('id');
      if ($id) $where[] = ['id', $id];
      $users = User::where($where)->get();
      

      默认返回所有用户,如果$where数组中存在任何东西,它会应用where condition

      【讨论】:

      • 优秀的解决方案(Y)
      【解决方案3】:

      我是从 Google 来到这里的。如果要迭代超过 5 个 if 语句,使用 switch 语句更有效

       if(empty($request->except('_token')))
              return 'false';
      
          $models = Vehicle::query();
          $request_query = $request->all();
          $year_switch = false;
      
          foreach ($request_query as $key => $field_value){
      
      
      
              if($field_value != 'any'){                
                  switch($field_value){
                      case 'X':                                            
                      case 'Y':
                          $year_switch = true; 
                      break;
                      case'Z':
                          //Dynamic
                          $models->where($key,'LIKE', $field_value);
                      break;
      
                  }                    
              }
          }
      

      【讨论】:

        【解决方案4】:
        You can use like this
        
        $validateUserDetail = User::query();
        if (!empty($userDetails['email'])) {
            $validateUserDetail->whereemail($userDetails['email']);
        }if (!empty($userDetails['cellphone'])) {
            $validateUserDetail->wherecellphone($userDetails['cellphone']);
        }
        $validateUserDetail->select('username');
        $validateUserDetail->get()
        

        【讨论】:

          【解决方案5】:

          使用 Laravel 很容易。只需执行以下操作:

          $query = User::query();
          
          if ($this == $that) {
            $query = $query->where('this', 'that');
          }
          
          if ($this == $another_thing) {
            $query = $query->where('this', 'another_thing');
          }
          
          if ($this == $yet_another_thing) {
            $query = $query->orderBy('this');
          }
          
          $results = $query->get();
          

          【讨论】:

          • 我的第一行有问题。可能会出现没有 where 参数的情况 :) 那么我该如何开始查询呢?
          • 如果你想开始一个裸查询,只需执行$query = User::query()。然后你可以添加所有条件 where 并在最后得到结果。
          • 优秀。顺便说一句,wunch 的评论应该是解决方案的一部分。
          • $query 没有更新吗?你需要一直做 $query = $query-> 吗?看起来有点奇怪。
          【解决方案6】:

          您可以通过以下示例传递动态值

          $user_auctions = $this->with('userAuctions')
                          ->where('users.id', '=', $id)
                          ->get();
          

          【讨论】:

            猜你喜欢
            • 2016-12-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多