Jak utworzyć wielokrotne zapytanie klauzuli Where przy użyciu Laravel Eloquent?

Używam Laravel Eloquent Query builder i mam zapytanie, w którym chcę WHERE klauzuli na wielu warunkach. To działa, ale nie jest eleganckie.

Przykład:

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

Czy jest lepszy sposób, aby to zrobić, czy powinienem trzymać się tej metody?

Author: Karl Hill, 2013-10-11

26 answers

In Laravel 5.3 (i nadal prawdziwe od 7.x ) możesz użyć bardziej ziarnistych wheres przekazywanych jako tablica:

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

Osobiscie nie znalazlem use-case dla tego tylko przez kilka where wywołań, ale faktem jest, ze mozna go uzyc.

Od czerwca 2014 roku można przekazać tablicę do where

Tak długo, jak chcesz używać operatora wheres and, możesz je grupować w ten sposób:

$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

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

Potem:

$results = User::where($matchThese)->get();

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

Powyższe spowoduje takie zapytanie:

SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)
 721
Author: Jarek Tkaczyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-02 00:50:09

Zakresy zapytań mogą pomóc w zwiększeniu czytelności kodu.

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

Zaktualizowanie tej odpowiedzi przykładem:

W modelu twórz metody zakresów w następujący sposób:

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

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

Następnie możesz wywołać ten zakres podczas budowania zapytania:

$users = User::active()->that()->get();
 106
Author: Luis Dalmolin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-11 16:32:20

Możesz użyć zapytań podrzędnych w funkcji anonimowej w następujący sposób:

 $results = User::where('this', '=', 1)
            ->where('that', '=', 1)
            ->where(function($query) {
                /** @var $query Illuminate\Database\Query\Builder  */
                return $query->where('this_too', 'LIKE', '%fake%')
                    ->orWhere('that_too', '=', 1);
            })
            ->get();
 88
Author: Juljan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-20 08:07:51

W tym przypadku przydałoby się coś takiego:

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

Powinno dostarczyć Ci zapytanie typu:

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')
 51
Author: alexglue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 17:53:05

Conditions using Array:

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

będzie produkować zapytanie jak poniżej:

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

Warunki przy użyciu funkcji anonimowej:

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

będzie produkować zapytanie jak poniżej:

SELECT * FROM TABLE WHERE column1 = value1 and (column2 = value2 or column3 = value3) and (column4 = value4 and column5 = value5)
 43
Author: srmilon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-19 08:24:26

Wielokrotne gdzie

    $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);
    }

Finally getting the result

    $result = $query->get();
 13
Author: Majbah Habib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-06 11:19:56

Metoda whereColumn może być przekazana tablicy wielu warunków. Warunki te zostaną połączone za pomocą operatora and.

Przykład:

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

Aby uzyskać więcej informacji, sprawdź tę sekcję dokumentacji https://laravel.com/docs/5.4/queries#where-clauses

 10
Author: Alex Quintero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-17 03:41:30
Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();

Lub

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

Lub

Model::where(['column_1' => 'value_1','column_2' => 'value_2'])->get();
 8
Author: DsRaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-28 04:45:12
$projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
    ['status','<>','Pending'],
    ['status','<>','Not Available']])
->orwhere([['owner', 'like', '%'.$input.'%'],
    ['status','<>','Pending'],
    ['status','<>','Not Available']])->get();
 6
Author: Lim Kean Phang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 17:55:18

Upewnij się, że zastosujesz inne filtry do zapytań podrzędnych, w przeciwnym razie or może zebrać wszystkie rekordy.

$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();
 5
Author: adamk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-26 14:39:38

Bez prawdziwego przykładu trudno jest wydać rekomendację. Jednak nigdy nie musiałem używać tak wielu klauzul WHERE w zapytaniu i może to wskazywać na problem ze strukturą Twoich danych.

Pomocne może być poznanie normalizacji danych: http://en.wikipedia.org/wiki/Third_normal_form

 3
Author: Aaron Cicali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-04 21:40:12

Możesz użyć eloquent w Laravel 5.3

Wszystkie wyniki

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

Częściowe wyniki

UserModel::where('id_user', $id_user)
                    ->where('estado', 1)
                    ->pluck('id_rol');
 3
Author: Cristhian Carreño,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-25 14:50:45

Z Eloquent łatwo jest utworzyć multiple where check:

Pierwszy: (Użyj prostego gdzie)

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

Drugi: (grupuj swoje gdzie wewnątrz tablicy)

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

Można również użyć warunkowe ( = ,, itd.) inside where like this:

$users = User::where('name', '=', $request['name'])
    ->where('surname', '=', $request['surname'])
    ->where('address', '<>', $request['address'])
    ...
    ->get();
 3
Author: Hedayatullah Sarwary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-17 21:05:49

Użyj warunku whereIn i podaj tablicę

$array = [1008,1009,1010];

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

 2
Author: Rahul Tathod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 09:40:48

Próbka kodu.

Po pierwsze:

$matchesLcl=[];

Tablica jest wypełniana za pomocą żądanej liczby / pętli warunków, incremently:

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

I dalej z wymowami takimi jak to wyrażenie:

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'));
 2
Author: CodeToLife,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-22 14:27:09

Możesz użyć klauzuli array in where, jak pokazano poniżej.

$result=DB::table('users')->where(array(
'column1' => value1,
'column2' => value2,
'column3' => value3))
->get();
 1
Author: Abhijeet Navgire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-15 14:08:15
DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function ($query) {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();
 1
Author: pardeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-13 10:14:12

Zgodnie z moją sugestią, jeśli robisz filtrowanie lub wyszukiwanie

Następnie należy wybrać:

        $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();
 1
Author: Dhruv Raval,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-23 09:59:30

Użyj Tego

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();
 1
Author: Sooraj Thekkepatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-13 09:38:26

Używając czystej elokwencji, zaimplementuj to w ten sposób. Ten kod zwraca wszystkich zalogowanych użytkowników, których konta są aktywne. $users = \App\User::where('status', 'active')->where('logged_in', true)->get();

 0
Author: slimgera00,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-08 10:58:46

Jeśli twoje warunki są takie (pasujące do pojedynczej wartości), prostszym bardziej eleganckim sposobem byłoby:

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

Ale jeśli potrzebujesz klauzul OR, upewnij się, że dla każdej klauzuli orWhere() powtórzysz warunki must meet.

    $player = Player::where([
            'name' => $name,
            'team_id' => $team_id
        ])
        ->orWhere([
            ['nickname', $nickname],
            ['team_id', $team_id]
        ])
 0
Author: Bardiya Bakhshandeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-02 01:20:19

Używamy tej Instrukcji, Aby uzyskać Użytkowników zgodnie z dwoma warunkami, typem klasyfikacji użytkowników i nazwą użytkownika.

Tutaj używamy dwóch warunków filtrowania podczas wpisywania, oprócz pobierania informacji o użytkowniku z tabeli profili, aby zmniejszyć liczbę zapytań.

$users = $this->user->where([
                    ['name','LIKE','%'.$request->name.'%'],
                    ['trainers_id','=',$request->trainers_id]
                    ])->with('profiles')->paginate(10);
 0
Author: Muhammed Ziyaüddin hatib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-28 10:22:56

Możesz używać na kilka sposobów,

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

Możesz również użyć w ten sposób,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();
 0
Author: Rashed Zaman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-06 10:23:32

Możesz to zrobić w następujący sposób, co jest najkrótszą drogą.

$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();
 0
Author: Kaleem Shoukat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-02-08 07:30:11
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'));
    }
}
 -5
Author: Muhammad Arslan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-10 20:00:08
$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);
}
 -29
Author: Yuri Lazo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-26 16:34:17