Laravel: dynamic where clause with Elouquent

2019-03-14 11:16发布

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

In theory:

  1. query
  2. query where(someParam1)
  3. query where(someParam2)
  4. query orderby(someParam3)
  5. query get

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.

4条回答
趁早两清
2楼-- · 2019-03-14 11:42
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()
查看更多
孤傲高冷的网名
3楼-- · 2019-03-14 11:43

You can pass dynamic value by below example

$user_auctions = $this->with('userAuctions')
                ->where('users.id', '=', $id)
                ->get();
查看更多
爷的心禁止访问
4楼-- · 2019-03-14 11:45

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

 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;

            }                    
        }
    }
查看更多
Viruses.
5楼-- · 2019-03-14 11:52

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

$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();
查看更多
登录 后发表回答