我想过滤产品列表。该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 查询。
最佳答案
这对我来说看起来更具可读性:
public function getProductsByQuery()
{
$q = Product::query();
if (request('location')) {
$q->whereIn('location_id', $this->toArray(request('location')));
}
if (request('category')) {
$q->whereIn('category_id', $this->toArray(request('category')));
}
return $q->paginate(config('app.products_per_page'));
}
关于php - Laravel/Eloquent 中按多个条件过滤模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652344/