【发布时间】:2018-08-08 12:01:00
【问题描述】:
我想过滤产品列表。该 API 可在路由 /q 中访问,我通过 /q?location=1,2&category=1,2,3 之类的过滤参数(如果未传递任何参数,它将获取所有位置/类别。
public function getProductsByQuery()
{
$commaSeparatedLocations = Input::get('location');
$commaSeparatedCategories = Input::get('category');
if ($commaSeparatedLocations == null){
$numberOfLocations = Location::count();
for ($i=0;$i<=$numberOfLocations;$i++)
{
$locationsArray[$i] = $i;
}
} else {
$locationsArray = $this->toArray($commaSeparatedLocations);
}
if ($commaSeparatedCategories == null){
$numberOfCategories = Category::count();
for ($i=0;$i<=$numberOfCategories;$i++)
{
$categoriesArray[$i] = $i;
}
} else {
$categoriesArray = $this->toArray($commaSeparatedCategories);
}
return $products = Product::whereIn('category_id', $categoriesArray)->whereIn('location_id', $locationsArray)->paginate(config('app.products_per_page'));
}
public function toArray($commaSeparatedString)
{
return explode(",",$commaSeparatedString);
}
而且,它有效。但我想知道如何改进我的代码。必须有一种更智能的方法,不需要那么多 SQL 查询。
【问题讨论】: