Add properties filtering and relationships in Product model
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user