6
0
Fork 0
jiqu-library-server/app/Models/ProductSpu.php

97 lines
2.0 KiB
PHP

<?php
namespace App\Models;
use App\Casts\JsonArray;
use App\Casts\Price;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
class ProductSpu extends Model
{
use HasDateTimeFormatter;
protected $casts = [
'images' => JsonArray::class,
'sell_price' => Price::class,
'market_price' => Price::class,
'cost_price' => Price::class,
'vip_price' => Price::class,
'attrs' => JsonArray::class,
'release_at' => 'datetime',
];
/**
* @var array
*/
protected $fillable = [
'name',
'subtitle',
'category_id',
'codcovere',
'images',
'sell_price',
'market_price',
'cost_price',
'vip_price',
'media',
'weight',
'attrs',
'stock',
'sales',
'release_at',
];
public function skus()
{
return $this->hasMany(ProductSku::class, 'spu_id');
}
public function specs()
{
return $this->hasMany(ProductSpuSpec::class, 'product_spu_id');
}
public function features()
{
return $this->belongsToMany(ProductFeature::class, 'product_spu_features', 'feature_id', 'spu_id');
}
/**
* 确认此主商品是否有 sku
*
* @return bool
*/
public function hasSku(): bool
{
return $this->skus()->exists();
}
/**
* 确认给定的 SKU 是否有效
*
* @param \App\Models\ProductSku $sku
* @return bool
*/
public function isValidProductSku(ProductSku $sku): bool
{
if ($this->getKey() !== $sku->spu_id) {
return false;
}
if (count($specs = (array) $sku->specs) === $this->specs->count()) {
foreach ($this->specs as $spec) {
$key = $spec->getKey();
if (! array_key_exists($key, $specs) || ! in_array($specs[$key], $spec->items)) {
return false;
}
}
return true;
}
return false;
}
}