我需要在一个中收集6个示波器,以便更轻松地使用它们。是否可以使用laravel?这是我使用它们的地方:
public function listSchoolsEndUser()
{
$schools_data = new School;
if ( Input::has('specialties') ) {
$schools_data = $schools_data->whereSpecialties(Input::get('specialties'));
}
if ( Input::has('district') ) {
$schools_data = $schools_data->whereDistrict(Input::get('district'));
}
if ( Input::has('municipality') ) {
$schools_data = $schools_data->whereMunicipality(Input::get('municipality'));
}
if ( Input::has('city') ) {
$schools_data = $schools_data->whereCity(Input::get('city'));
}
if ( Input::has('type') ) {
$schools_data = $schools_data->whereType(Input::get('type'));
}
if ( Input::has('financing') ) {
$schools_data = $schools_data->whereFinancing(Input::get('financing'));
}
$schools_data = $schools_data->paginate(12);
return $schools_data;
}
我需要多次使用这些过滤器,并且我没有理由再次重复相同的代码。
编辑:我的示例范围范围
public function scopeWhereDistrict($query, $districts)
{
if(! is_array($districts))
{
$districts = [$districts];
}
return $query->where(function($q) use ($districts)
{
foreach ($districts as $district)
{
$q->whereHas('city.municipality', function ($q) use ($district) {
$q->where('district_id', '=', $district);
});
}
});
}
答案 0 :(得分:3)
循环浏览所有输入并添加where应该有效:
$schools_data = School::query();
$filters = Input::only('specialities', 'district', 'municipality', 'city', 'type', 'financing');
foreach($filters as $filter => $value){
call_user_func(array($schools_data, 'where' . studly_case($filter)), $value);
}
return $schools_data->paginate(12);