php - anidadas - consultas eloquent laravel
¿Cómo crear una consulta de múltiples cláusulas en el lugar utilizando Laravel Eloquent? (12)
Asegúrese de aplicar cualquier otro filtro a las consultas secundarias, de lo contrario podría recopilar todos los registros.
$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();
Estoy utilizando el generador de consultas Laravel Eloquent y tengo una consulta donde quiero una cláusula WHERE
en múltiples condiciones. Funciona, pero no es elegante.
Ejemplo:
$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();
¿Hay una mejor manera de hacer esto, o debo seguir con este método?
El método whereColumn
puede pasar una matriz de múltiples condiciones. Estas condiciones se unirán utilizando el operador and
.
Ejemplo:
$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();
Para obtener más información, consulte esta sección de la documentación https://laravel.com/docs/5.4/queries#where-clauses
Los ámbitos de consulta pueden ayudarlo a permitir que su código sea más legible.
http://laravel.com/docs/eloquent#query-scopes
Actualizando esta respuesta con algún ejemplo:
En su modelo, cree métodos de alcance como este:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeThat($query)
{
return $query->where('that', '=', 1);
}
Luego, puedes llamar a estos ámbitos mientras construyes tu consulta:
$users = User::active()->that()->get();
Puede usar array en la cláusula where como se muestra a continuación.
$result=DB::table('users')->where(array(
'column1' => value1,
'column2' => value2,
'column3' => value3))
->get();
Puedes usar subconsultas en funciones anónimas como esta:
$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();
Sin un ejemplo real, es difícil hacer una recomendación. Sin embargo, nunca he necesitado usar tantas cláusulas WHERE en una consulta y puede indicar un problema con la estructura de sus datos.
Puede ser útil para usted aprender acerca de la normalización de datos: http://en.wikipedia.org/wiki/Third_normal_form
Cláusulas múltiples donde
$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);
}
finalmente obteniendo el resultado
$result = $query->get();
Condiciones de uso de Array:
$users = User::where([
'column1' => value1,
'column2' => value2,
'column3' => value3
])->get();
Producirá consulta como bramido:
SELECT * FROM TABLE WHERE column1=value1 and column2=value2 and column3=value3
Condiciones de uso de la función antánima:
$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();
Producirá consulta como bramido:
SELECT * FROM TABLE WHERE column1=value1 and (column2=value2 or column3=value3) and (column4=value4 and column5=value5)
$projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
['status','<>','Pending'],
['status','<>','Not Available']])
->orwhere([['owner', 'like', '%'.$input.'%'],
['status','<>','Pending'],
['status','<>','Not Available']])->get();
$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);
}
Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();
O
// If you are looking for equal value then no need to add =
Model::where('column_1','value_1')->where('column_2','value_2')->get();
O
Model::where(['column_1' => 'value_1','column_2' => 'value_2'])->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'));
}
}