Add properties filtering and relationships in Product model

This commit is contained in:
2026-02-05 01:08:07 +05:00
parent 45bc0b61a1
commit 38fa0e2e45
11 changed files with 227 additions and 2 deletions

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Models\Ecommerce\Product\Product\Concerns;
trait HasPropertiesJson
{
/**
* Initialize the trait
*/
public function initializeHasPropertiesJson()
{
$this->casts['properties_json'] = 'array';
}
/**
* Sync properties to JSON column
*/
public function syncPropertiesJson(): void
{
$this->load(['properties.attribute', 'properties.values.value']);
$propertiesJson = [];
foreach ($this->properties as $property) {
$attributeSlug = $property->attribute->slug;
if (! isset($propertiesJson[$attributeSlug])) {
$propertiesJson[$attributeSlug] = [];
}
foreach ($property->values as $value) {
// We want to store both the key (for standard values) and the custom value
// so we can filter by either.
if ($value->value) {
$propertiesJson[$attributeSlug][] = $value->value->key;
}
if ($value->product_custom_value) {
$propertiesJson[$attributeSlug][] = $value->product_custom_value;
}
}
// Unique values just in case
$propertiesJson[$attributeSlug] = array_values(array_unique($propertiesJson[$attributeSlug]));
}
$this->properties_json = $propertiesJson;
$this->saveQuietly();
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Models\Ecommerce\Product\Product;
use App\Models\Concerns\HasSchemalessAttributes;
use App\Models\Ecommerce\Product\Product\Concerns\HasPropertiesJson;
use App\Models\Ecommerce\Product\Product\Concerns\ProductFrontEndHelpers;
use App\Models\Ecommerce\Product\Product\Concerns\ProductMedia;
use App\Models\Ecommerce\Product\Product\Concerns\ProductProperties;
@@ -31,6 +32,11 @@ class Product extends Model implements HasMedia, Viewable
*/
use HasSchemalessAttributes;
/**
* Has Properties Json
*/
use HasPropertiesJson;
/**
* Has Slug (spatie/laravel-sluggable)
*/
@@ -117,5 +123,6 @@ class Product extends Model implements HasMedia, Viewable
'is_visible',
'colour',
'size',
'properties_json',
];
}

View File

@@ -69,4 +69,12 @@ class ProductAttributeValue extends Model
{
return $this->belongsTo(AttributeValue::class, 'attribute_value_id');
}
/**
* Product Property
*/
public function productProperty(): BelongsTo
{
return $this->belongsTo(ProductProperty::class, 'product_attribute_id');
}
}