又又发 Package 了~拯救 where 地狱的 Eloquent 过滤器~
你可能写过这样的函数:
public function getAppsList(AppListSearchRequest $searchRequest)
{
$projects = Project::statusActive()->with('projectable', 'user')->where('projectable_type', 'App\App');
if ($searchRequest->min_price) {
$projects = $projects->where('price', '>=', $searchRequest->min_price);
}
if ($searchRequest->max_price) {
$projects = $projects->where('price', '<=', $searchRequest->max_price);
}
if ($searchRequest->min_monthly_downloads || $searchRequest->max_monthly_downloads || $searchRequest->min_monthly_income || $searchRequest->max_monthly_income) {
$projects = $projects->whereIn('projectable_id', function ($q) use ($searchRequest) {
$q = $q->from('apps');
if ($searchRequest->min_monthly_downloads) {
$q = $q->where('monthly_downloads', '>=', $searchRequest->min_monthly_downloads);
}
if ($searchRequest->max_monthly_downloads) {
$q = $q->where('monthly_downloads', '<=', $searchRequest->max_monthly_downloads);
}
if ($searchRequest->min_monthly_income) {
$q = $q->where('monthly_income', '>=', $searchRequest->min_monthly_income);
}
if ($searchRequest->max_monthly_income) {
$q = $q->where('monthly_income', '<=', $searchRequest->max_monthly_income);
}
$q->lists('id');
});
}
// platforms
$platforms = $searchRequest->getPlatformsArray();
$projects = $this->withAnyTags($projects, $platforms);
// Categories
if (@$searchRequest->category[0] || @$searchRequest->category[1]) {
$categories = $searchRequest->getCategoriesArray();
$projects = $this->withAnyTags($projects, $categories);
}
$projects = $projects->orderByTop()->paginate($searchRequest->page_size);
return $projects;
}
一大堆where头晕? 那么你需要 zgldh/laravel-query-filter
以后只需要
- 定义好过滤器
- 准备好过滤参数
- 得到过滤后的结果
就这么简单! 详情点击 zgldh/laravel-query-filter Github