常规写法
$query = User::query();
if ($request->username) {
$query->where('username', 'LIKE', "%$request->username%");
}
if ($request->email) {
$query->where('email', 'LIKE', "%$request->email%");
}
if ($request->address) {
$query->where('address', 'LIKE', "%$request->address%");
}
if ($request->occupation) {
$query->where('occupation', 'LIKE', "%$request->occupation%");
}
return $query->get();
优化写法
$query = User::query();
foreach(['username', 'email'] as $where)
if ($request->{$where}) {
$query->where($where, 'LIKE', "%$request->{$where}%");
}
}
return $query->get();
|