【发布时间】:2018-03-31 14:11:47
【问题描述】:
我正在为某些产品开发过滤器。我的大部分工作都在工作,但是我遇到了一个不可能的错误where 子句。
该表包含单个产品的多行,我试图匹配每个产品的多个条件,这导致它失败。
如果您对此有意见,或者可能有解决此问题的方法,我将不胜感激。
数据库表如下所示:
------------------------------------------ |标识 |过滤键 |过滤器值 |产品编号 | ------------------------------------------ |1 |颜色 |枪色 | 1 | |2 |颜色 |银 | 1 | |3 |尺寸 | 750cc | 1 | |4 |尺寸 | 1000cc | 1 | |5 |颜色 |红色 | 2 | |6 |颜色 |蓝色 | 2 | |7 |尺寸 | 750cc | 2 | |8 |尺寸 | 1000cc | 2 | ------------------------------------------过滤器看起来像这样:
public function scopeFilterProduct($query, $filters)
{
$this->filters = $filters;
if (count ($this->filters) === 1 && isset($this->filters[0]))
{
return $query;
}
$query->join('product_filters', 'products.id', '=', 'product_filters.product_id')->Where(function($query){
foreach ($this->filters as $filter => $vals)
{
$this->filter = $filter;
$this->vals = $vals;
$query->Where(function ($query){
$query->Where('filterKey', $this->filter);
$query->Where(function($query){
foreach ($this->vals as $val){
$query->orWhere('filterValue', $val);
}
$this->vals = null;
});
});
$this->filter = null;
};
});
return $query;
}
然后输出以下 SQL 语句:
select
distinct
`products`.`id`
, `product_id`
from
`products`
inner join
`product_filters`
on
`products`.`id` = `product_filters`.`product_id`
where
(
(`filterKey` = 'Colour' and (`filterValue` = 'gunmetal'))
and
(`filterKey` = 'Size' and (`filterValue` = '750cc'))
)
and
`products`.`deleted_at` is null
如果选中,如屏幕截图所示,则页面上应仅显示“产品一”。
【问题讨论】:
-
这称为集合划分。遵循的逻辑是“获取不存在选定过滤器的产品”