feat: add filtering for product detail attribute options based on available variant values
This commit is contained in:
@@ -293,6 +293,8 @@ class ProductService
|
||||
'variants.definitions.productAttribute.attribute.options',
|
||||
]);
|
||||
|
||||
$this->filterProductDetailAttributeOptions($product);
|
||||
|
||||
$selectedVariant = $variantId !== null
|
||||
? $product->variants->firstWhere('id', $variantId)
|
||||
: $product->variants->first(fn (ProductVariant $variant) => $variant->stock > 0);
|
||||
@@ -313,4 +315,36 @@ class ProductService
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
protected function filterProductDetailAttributeOptions(Product $product): void
|
||||
{
|
||||
$availableValuesByAttributeId = [];
|
||||
|
||||
foreach ($product->variants as $variant) {
|
||||
foreach ($variant->definitions as $definition) {
|
||||
$attributeId = $definition->productAttribute?->attribute_id;
|
||||
|
||||
if ($attributeId === null || $definition->value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$availableValuesByAttributeId[$attributeId][$definition->value] = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($product->attributes as $attribute) {
|
||||
if (! $attribute->relationLoaded('options')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$availableValues = $availableValuesByAttributeId[$attribute->id] ?? [];
|
||||
|
||||
$attribute->setRelation(
|
||||
'options',
|
||||
$attribute->options
|
||||
->filter(fn ($option): bool => array_key_exists($option->value, $availableValues))
|
||||
->values()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user