I have a switch
statement that I want to query my Database
based on case clauses
; and I want to use Where clauses
to achieve my goal. I want to incrementally add where clauses to my User
model based on satisfied conditions. example :
switch($key){
case 'province':
//User::where('province', '=', $value);
break;
case 'city':
//User::where('city', '=', $value);
break;
case 'specialty':
//User::where('specialty', '=', $value);
break;
default:
break;
}
I want to use Eloquent Models instead of Query Builder. but I don't know how to do this.
This is how you do it:
// instantiate the query
$query = User::query();
// add wheres
switch / foreach or whatever
{
$query->where(...);
}
// other methods if needed
$query->orderBy(..)
// execute
$users = $query->get();
If you want to add clauses incrementally, a loop would be better than a switch statement. Assuming that your information is coming from user input I'd do it like so:
$input = Input::only(['province', 'city', 'speciality']);
$user = new User;
foreach($input as $key => $value) {
if(!empty($value)) {
$user = $user->where($key, $value);
}
}
$users = $user->get();
return View::make('foo', compact('users'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.