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 ingenious.
Example:
$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();
Is there a better way to do this, or should I stick with this method?
Thank you!!
You can use Conditions using Array:
$users = User::where([
'column1' => value1,
'column2' => value2,
'column3' => value3
])->get();
That Will produce query like bellow:
SELECT * FROM TABLE WHERE column1=value1 and column2=value2 and column3=value3;
Conditions using Antonymous Function:
$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();
That Will produce query like bellow:
SELECT * FROM TABLE WHERE column1=value1 and
(column2=value2 or column3=value3) and (column4=value4 and column5=value5);
0 comments:
Post a Comment
Thanks