Laravel:带有 Elouquent 的动态 where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30942556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:48:39  来源:igfitidea点击:

Laravel: dynamic where clause with Elouquent

laraveleloquent

提问by be-codified

I am calling URL with search params which are dynamic. How could I form proper Eloquent query?

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

In theory:

理论上:

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

I need this kind of structure so I can use where clause if param exists. If there is some other way in Laravel, please let me know.

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

回答by BakerStreetSystems

It's easy with Laravel. Just do something like this:

使用 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();

回答by Nishabh Mistry

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()

回答by CTully12

I came here from Google. If you are going to be iterating over more then 5 if statements, its more effective to use a switch statement

我从谷歌来到这里。如果您要迭代超过 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;

            }                    
        }
    }

回答by Nikunj K.

You can pass dynamic value by below example

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

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