gpt4 book ai didi

php - 如何在 Laravel 中制作带有产品属性的智能过滤器

转载 作者:行者123 更新时间:2023-11-29 15:42:26 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com