【发布时间】:2018-03-22 07:46:19
【问题描述】:
我想用以下条件过滤目标、价格和产品等过滤器的商店模型:
- 它们都允许多选,所以我总是会传递一个数组。
- 我总是必须使用 AND 运算符。如果我尝试按 price = $ 和 target = men 进行过滤,则查询应该类似于“WHERE price_range = $ AND target = men”。
当我尝试进行过滤时,查询总是返回错误的结果。例如,我有一个 price_range = $ 和 target = men 的商店。当我按 price_range = $ 和 target = women 过滤时,该商店出现在结果中,这是错误的。
这是我的商店模型:
<?php
namespace App;
class Store extends Model
{
public function values()
{
return $this->belongsToMany('App\Value');
}
public function targets()
{
return $this->belongsToMany('App\Target');
}
public function products()
{
return $this->belongsToMany('App\Product');
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function scopePrices($query, $priceRanges = [])
{
if ($priceRanges) {
return $query->whereIn('price_range', $priceRanges);
}
}
public function scopeValues($query, $values = [])
{
if ($values) {
return $query->whereHas('values', function ($query) use ($values) {
$query->whereIn('name', $values);
});
}
}
public function scopeTargets($query, $targets = [])
{
if ($targets) {
return $query->whereHas('targets', function ($query) use ($targets) {
$query->whereIn('name', $targets);
});
}
}
public function scopeProducts($query, $products = [])
{
if ($products) {
return $query->whereHas('products', function ($query) use ($products) {
$query->whereIn('name', $products);
});
}
}
}
这是我从 StoresController 获得的 getStores():
public function getStores()
{
$stores = Store::active()
->prices(request('price_ranges'))
->values(request('values'))
->targets(request('targets'))
->products(request('products'))
->orderBy('name')
->get();
return response()->json($stores);
}
我想用范围来做这件事,因为我认为这是一种干净的方法。提前感谢您的帮助:)
【问题讨论】:
标签: php laravel laravel-5.6