복붙노트

Laravel Eloquent를 사용하여 여러 where 절을 만드는 방법은 무엇입니까?

PHP

Laravel Eloquent를 사용하여 여러 where 절을 만드는 방법은 무엇입니까?

Laravel Eloquent 쿼리 빌더를 사용하고 있으며 여러 조건에서 WHERE 절을 원할 때 쿼리가 있습니다. 그것은 작동하지만 우아하지 않습니다.

예:

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

이 작업을 수행하는 더 좋은 방법이 있습니까, 아니면이 방법을 고수해야합니까?

해결법

  1. ==============================

    1.Laravel 5.3에서는 배열로 전달되는보다 세분화 된 wheres를 사용할 수 있습니다.

    Laravel 5.3에서는 배열로 전달되는보다 세분화 된 wheres를 사용할 수 있습니다.

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

    개인적으로이 경우에는 여러 곳에서 사용 사례를 찾지 못했지만 실제로는 사용할 수 있습니다.

    2014 년 6 월부터 배열을 어디로 전달할 수 있습니까?

    모든 wheres 사용 및 연산자를 원할 경우, 다음과 같이 그룹화 할 수 있습니다.

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

    그때:

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

    위와 같은 쿼리 결과 :

    SELECT * FROM users
      WHERE (field = value AND another_field = another_value AND ...)
      OR (yet_another_field = yet_another_value AND ...)
    
  2. ==============================

    2.쿼리 범위는 코드를보다 쉽게 ​​읽을 수 있도록 도와줍니다.

    쿼리 범위는 코드를보다 쉽게 ​​읽을 수 있도록 도와줍니다.

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

    몇 가지 예를 들어이 대답 업데이트 :

    모델에서 다음과 같은 범위 메소드를 작성하십시오.

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

    그런 다음 쿼리를 작성하는 동안이 범위를 호출 할 수 있습니다.

    $users = User::active()->that()->get();
    
  3. ==============================

    3.다음과 같은 익명 함수로 하위 쿼리를 사용할 수 있습니다.

    다음과 같은 익명 함수로 하위 쿼리를 사용할 수 있습니다.

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

    4.이 경우 다음과 같이 사용할 수 있습니다.

    이 경우 다음과 같이 사용할 수 있습니다.

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

    다음과 같은 쿼리를 제공해야합니다.

    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')
    
  5. ==============================

    5.배열을 사용하는 조건 :

    배열을 사용하는 조건 :

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

    다음과 같은 쿼리를 생성합니다.

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

    익명 기능을 사용하는 조건 :

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

    다음과 같은 쿼리를 생성합니다.

    SELECT * FROM TABLE WHERE column1=value1 and (column2=value2 or column3=value3) and (column4=value4 and column5=value5)
    
  6. ==============================

    6.여러 where 절

    여러 where 절

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

    결국 결과를 얻는다.

        $result = $query->get();
    
  7. ==============================

    7.whereColumn 메서드는 여러 조건의 배열을 전달할 수 있습니다. 이러한 조건은 and 연산자를 사용하여 조인됩니다.

    whereColumn 메서드는 여러 조건의 배열을 전달할 수 있습니다. 이러한 조건은 and 연산자를 사용하여 조인됩니다.

    예:

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

    자세한 내용은이 절의 설명서를 참조하십시오. https://laravel.com/docs/5.4/queries#where-clauses

  8. ==============================

    8.하위 쿼리에 다른 필터를 적용하십시오. 그렇지 않으면 또는 모든 레코드를 수집 할 수 있습니다.

    하위 쿼리에 다른 필터를 적용하십시오. 그렇지 않으면 또는 모든 레코드를 수집 할 수 있습니다.

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

    9.

    Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();
    

    또는

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

    또는

    Model::where(['column_1' => 'value_1','column_2' => 'value_2'])->get();
    
  10. ==============================

    10.실제 사례가 없으면 추천을하기가 어렵습니다. 그러나 쿼리에서 WHERE 절을 많이 사용할 필요가 없으며 데이터 구조에 문제가 있음을 나타낼 수 있습니다.

    실제 사례가 없으면 추천을하기가 어렵습니다. 그러나 쿼리에서 WHERE 절을 많이 사용할 필요가 없으며 데이터 구조에 문제가 있음을 나타낼 수 있습니다.

    데이터 정규화에 대해 배우는 것이 도움이 될 수 있습니다. http://en.wikipedia.org/wiki/Third_normal_form

  11. ==============================

    11.Laravel 5.3에서 웅변을 사용할 수 있습니다.

    Laravel 5.3에서 웅변을 사용할 수 있습니다.

    모든 결과

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

    부분 결과

    UserModel::where('id_user', $id_user)
                        ->where('estado', 1)
                        ->pluck('id_rol');
    
  12. ==============================

    12.

    $projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
        ['status','<>','Pending'],
        ['status','<>','Not Available']])
    ->orwhere([['owner', 'like', '%'.$input.'%'],
        ['status','<>','Pending'],
        ['status','<>','Not Available']])->get();
    
  13. ==============================

    13.whereIn 조건을 사용하고 배열을 전달하십시오.

    whereIn 조건을 사용하고 배열을 전달하십시오.

    $ array = [1008,1009,1010];

    사용자 :: whereIn ( 'users.id', $ 배열) -> get ();

  14. ==============================

    14.아래와 같이 where 절에서 array를 사용할 수 있습니다.

    아래와 같이 where 절에서 array를 사용할 수 있습니다.

    $result=DB::table('users')->where(array(
    'column1' => value1,
    'column2' => value2,
    'column3' => value3))
    ->get();
    
  15. ==============================

    15.

    DB::table('users')
                ->where('name', '=', 'John')
                ->orWhere(function ($query) {
                    $query->where('votes', '>', 100)
                          ->where('title', '<>', 'Admin');
                })
                ->get();
    
  16. ==============================

    16.

    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'));
        }
    }
    
  17. ==============================

    17.

    $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);
    }
    
  18. from https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent by cc-by-sa and MIT license