How to Create Multiple Where Clause Query Using Laravel Eloquent?

前端 未结 24 1098
一整个雨季
一整个雨季 2020-11-22 14:30

I\'m using the Laravel Eloquent query builder and I have a query where I want a WHERE clause on multiple conditions. It works, but it\'s not elegant.

E

相关标签:
24条回答
  • 2020-11-22 15:19

    if your conditionals are like that (matching a single value), a simple more elegant way would be:

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

    but if you need to OR the clauses then make sure for each orWhere() clause you repeat the must meet conditionals.

        $player = Player::where([
                'name' => $name,
                'team_id' => $team_id
            ])
            ->orWhere([
                ['nickname', $nickname],
                ['team_id', $team_id]
            ])
    
    0 讨论(0)
  • 2020-11-22 15:21

    As per my suggestion if you are doing filter or searching

    then you should go with :

            $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();
    
    0 讨论(0)
  • 2020-11-22 15:22

    use whereIn condition and pass the array

    $array = [1008,1009,1010];

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

    0 讨论(0)
  • 2020-11-22 15:23

    We use this instruction to obtain users according to two conditions, type of user classification and user name.

    Here we use two conditions for filtering as you type in addition to fetching user information from the profiles table to reduce the number of queries.

    $users = $this->user->where([
                        ['name','LIKE','%'.$request->name.'%'],
                        ['trainers_id','=',$request->trainers_id]
                        ])->with('profiles')->paginate(10);
    
    0 讨论(0)
  • 2020-11-22 15:26

    Use This

    $users = DB::table('users')
                        ->where('votes', '>', 100)
                        ->orWhere('name', 'John')
                        ->get();
    
    0 讨论(0)
  • 2020-11-22 15:26

    Using pure Eloquent, implement it like so. This code returns all logged in users whose accounts are active. $users = \App\User::where('status', 'active')->where('logged_in', true)->get();

    0 讨论(0)
提交回复
热议问题