作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Laravel 5.8 进行电子商务,现在我正在尝试进行智能过滤。
我有 4 个表(产品、属性、attribute_values、product_attributes)。
id name direction_id
----------------------------------
1 Product 1 1
2 Product 2 2
3 Product 3 1
4 Product 4 1
id name
-------------------
1 HDD
2 RAM
id attribute_id value
------------------------------
1 1 1TB
2 1 500GB
3 2 8GB
4 2 32GB
id product_id value_id
---------------------------
1 1 1
2 1 3
3 2 1
4 2 4
5 3 1
6 4 4
现在我只想显示一个方向的产品属性和值。例如。如果direction_id = 1我只想显示 HDD (1TB)、RAM(8GB、32GB)。
有什么想法可以制作这种过滤器并过滤产品。我只是想出了这个显示属性和值的解决方案。
对于属性
select distinct a.*
from products p
left join product_attributes pa
on pa.product_id = p.id
left join attribute_values v
on v.id = pa.value_id
left join attributes a
on a.id = v.attribute_id
where p.direction_id = 1
对于值
select distinct v.*
from products p
left join product_attributes pa
on pa.product_id = p.id
left join attribute_values v
on v.id = pa.value_id
where p.direction_id = 1
最佳答案
Laravel 中的解决方案将实现关系,如下所示:
// class Product extends Model ('products' table)
public function attributeValues()
{
return $this->belongsToMany(AttributeValue::class, 'product_attributes', 'product_id', 'value_id');
}
// class AttributeValue extends Model ('attribute_values' table)
public function attribute()
{
return $this->belongsTo(Attribute::class, 'attribute_id', 'id');
}
// retrieve engine for direction '1':
$attributesValues = [];
Product::query()
->where(['direction' => 1])
->each(function(Product $product) use (&$attributesValues) {
$product->attributeValues()->each(function(AttributeValue $attributeValue) use (&$attributesValues) {
$attributesValues[$attributeValue->attribute->name][] = $attributeValue->value;
});
});
dd($attributesValues);
关于php - 如何在 Laravel 中制作带有产品属性的智能过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463157/
我是一名优秀的程序员,十分优秀!