【发布时间】:2016-07-19 03:16:28
【问题描述】:
嗨,我有一个用于搜索表单的大型查询,我只是想知道如何将它移到模型中,我已经阅读了查询范围等等,但这比仅仅复杂得多为 1 个字段搜索 1 个表,我很迷茫,感谢任何帮助!
public function index()
{
$input = Request::all();
$date = \Carbon\Carbon::now()->subMinute(30);
$query = User::rightJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id');
if (isset($input ['minAge']) && $input['minAge']) {
$minAge = $input['minAge'];
$maxDate = \Carbon\Carbon::today()->subYears($minAge)->endOfDay();
}
if (isset($input ['maxAge']) && $input['maxAge']) {
if ($input['maxAge'] < $input['minAge']) {
$maxAge = $input['minAge'];
}
else {
$maxAge = $input['maxAge'];
}
$minDate = \Carbon\Carbon::today()->subYears($maxAge + 1);
}
if (isset($input['u']) && $input['u'])
$query->where('users.username', '=', $input['u']);
if (isset($input['p']) && $input['p'])
$query->where('user_profiles.postcode', '=', $input ['p']);
if (isset($input['o1']) && $input['o1'])
$query->where('users.last_online','>=',$date);
if (isset($input['o2']) && $input['o2'])
$query->whereNotNull('user_profiles.avatar');
if (isset($input ['o3']) && $input['o3'])
$query->orderBy('users.type', 'ASC');
if (isset($input ['minAge']) && $input['minAge'])
$query->whereBetween('user_profiles.dob', [$minDate, $maxDate]);
if (isset($input ['g']))
$query->whereIn('user_profiles.gender',$input ['g']);
$query->orderBy('users.last_online', 'DESC');
$users = $query->paginate(1);
return view('view', compact('users'));
}
【问题讨论】: