Laravel Archent를 사용하여 Multiple Where 절 쿼리를 작성하는 방법
Laravel Archent 쿼리 빌더를 사용하고 있는데, 어디서 원하는지 질문이 있습니다.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();
더 좋은 방법이 있을까요, 아니면 이 방법을 계속 사용해야 할까요?
Larabel 5.3(및 7.x 시점에서도 마찬가지)에서는 어레이로 전달되는 보다 세밀한 위치를 사용할 수 있습니다.
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
개인적으로는 여러 개에 걸친 사용 사례를 찾을 수 없었습니다.where
전화는 하지만 사실은 그걸 사용할 수 있어요
2014년 6월부터 어레이는where
당신이 모든 것을 원한다면wheres
사용하다and
오퍼레이터는 다음과 같이 그룹화할 수 있습니다.
$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 ...)
다음과 같이 어나니머스 함수에서 서브쿼리를 사용할 수 있습니다.
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where(
function($query) {
return $query
->where('this_too', 'LIKE', '%fake%')
->orWhere('that_too', '=', 1);
})
->get();
쿼리 범위를 사용하면 코드를 더 잘 읽을 수 있습니다.
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();
어레이를 사용하는 조건:
$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)
이 경우 다음과 같은 기능을 사용할 수 있습니다.
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')
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();
multiple 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();
그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
$projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
['status','<>','Pending'],
['status','<>','Not Available']])
->orwhere([['owner', 'like', '%'.$input.'%'],
['status','<>','Pending'],
['status','<>','Not Available']])->get();
서브 쿼리에 다른 필터를 적용해야 합니다.그렇지 않으면또는 모든 레코드를 수집할 수 있습니다.
$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();
Alturnal을 사용하면 여러 개의 체크 위치를 쉽게 만들 수 있습니다.
첫 번째: (간단한 장소에서 사용)
$users = User::where('name', $request['name'])
->where('surname', $request['surname'])
->where('address', $request['address'])
...
->get();
두 번째: (어레이 내 장소를 그룹화)
$users = User::where([
['name', $request['name']],
['surname', $request['surname']],
['address', $request['address']],
...
])->get();
다음과 같은 경우에 조건부(=, <> 등)를 사용할 수도 있습니다.
$users = User::where('name', '=', $request['name'])
->where('surname', '=', $request['surname'])
->where('address', '<>', $request['address'])
...
->get();
Larabel 5.3에서는 웅변을 사용할 수 있습니다.
모든 결과
UserModel::where('id_user', $id_user)
->where('estado', 1)
->get();
부분 결과
UserModel::where('id_user', $id_user)
->where('estado', 1)
->pluck('id_rol');
필터나 검색을 하고 있는 경우, 제가 제안하는 바와 같이
다음 명령어를 사용합니다.
$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();
여러 가지 방법으로 사용할 수 있습니다.
$results = User::where([
['column_name1', '=', $value1],
['column_name2', '<', $value2],
['column_name3', '>', $value3]
])->get();
이렇게도 쓸 수 있고
$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<', $value2);
$results = $results->where('column3','>', $value3);
$results = $results->get();
다음과 같이 where 절에서 배열을 사용할 수 있습니다.
$result=DB::table('users')->where(array(
'column1' => value1,
'column2' => value2,
'column3' => value3))
->get();
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
사용방법
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
코드의 샘플.
첫 번째:
$matchesLcl=[];
원하는 조건의 수/루프를 사용하여 배열이 여기에 채워집니다(증분:
$matchesLcl['pos']= $request->pos;
$matchesLcl['operation']= $operation;
//+......+
$matchesLcl['somethingN']= $valueN;
더 나아가 다음과 같은 웅변으로 위축된 표현을 사용합니다.
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'));
순수한 웅변을 사용하여 그렇게 구현합니다.이 코드는 계정이 활성 상태인 로그인한 모든 사용자를 반환합니다. $users = \App\User::where('status', 'active')->where('logged_in', true)->get();
조건(단일값 포함)이 이와 같다면, 보다 심플하고 우아한 방법은 다음과 같습니다.
$results = User::where([
'this' => value,
'that' => value,
'this_too' => value,
...
])
->get();
단, 구를 OR해야 할 경우 각 구 또는 Where() 구에 대해 를 반복하여 조건을 충족해야 합니다.
$player = Player::where([
'name' => $name,
'team_id' => $team_id
])
->orWhere([
['nickname', $nickname],
['team_id', $team_id]
])
사용자 분류 유형과 사용자 이름이라는 두 가지 조건에 따라 사용자를 얻기 위해 이 지침을 사용합니다.
여기에서는 프로파일테이블에서 사용자 정보를 가져오는 것 외에 사용자가 입력할 때 두 가지 조건을 필터링하여 쿼리 수를 줄입니다.
$users = $this->user->where([
['name','LIKE','%'.$request->name.'%'],
['trainers_id','=',$request->trainers_id]
])->with('profiles')->paginate(10);
가장 빠른 방법인 다음과 같이 할 수 있습니다.
$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();
웅변에서는 다음과 같이 할 수 있습니다.
$results = User::where('this', '=', 1)
->orWhere('that', '=', 1)
->orWhere('this_too', '=', 1)
->orWhere('that_too', '=', 1)
->orWhere('this_as_well', '=', 1)
->orWhere('that_as_well', '=', 1)
->orWhere('this_one_too', '=', 1)
->orWhere('that_one_too', '=', 1)
->orWhere('this_one_as_well', '=', 1)
->orWhere('that_one_as_well', '=', 1)
->get();
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'));
}
}
$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);
}
언급URL : https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent
'it-source' 카테고리의 다른 글
MariaDB/SQL 레코드 수를 가져오는 가장 효율적인 방법 (0) | 2022.11.01 |
---|---|
PHP로 JSON 데이터를 생성하는 방법은 무엇입니까? (0) | 2022.11.01 |
작곡가를 어떻게 운영하죠? (0) | 2022.11.01 |
상대 Import - Module Not Found Error :x라는 이름의 모듈이 없습니다. (0) | 2022.11.01 |
WooCommerce 주문 세부 정보 가져오는 방법 (0) | 2022.11.01 |