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

131 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use App\Casts\JsonArray;
use App\Casts\Price;
use App\Traits\Release;
use App\Traits\SkuInfo;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
class ProductSku extends Model
{
use Filterable;
use HasDateTimeFormatter;
use Release;
use SkuInfo;
public const STATUS_INVALID = -1; // 无效的
public const STATUS_ONLINE = 1; // 已上架
public const STATUS_OFFLINE = 2; // 已下架
/**
* @var array
*/
protected $casts = [
'images' => JsonArray::class,
'sell_price' => Price::class,
'market_price' => Price::class,
'cost_price' => Price::class,
'vip_price' => Price::class,
'attrs' => JsonArray::class,
'specs' => 'json',
'release_at' => 'datetime',
];
/**
* @var array
*/
protected $fillable = [
'spu_id',
'name',
'subtitle',
'category_id',
'codcovere',
'images',
'sell_price',
'market_price',
'cost_price',
'vip_price',
'media',
'weight',
'shipping_template_id',
'attrs',
'specs',
'stock',
'sales',
'release_at',
];
/**
* 仅查询已上架的商品
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOnline($query)
{
return $query->whereNotNull('release_at')->whereRelation('category', 'is_show', true);
}
/**
* 此商品所属的 SPU
*/
public function spu()
{
return $this->belongsTo(ProductSpu::class, 'spu_id');
}
/**
* 此商品所属的分类
*/
public function category()
{
return $this->belongsTo(ProductCategory::class, 'category_id');
}
/**
* 此商品所属的分区
*/
public function parts()
{
return $this->belongsToMany(ProductPart::class, ProductPartSku::class, 'sku_id', 'part_id');
}
/**
* 确认此商品是否已上架
*
* @return bool
*/
public function isOnline(): bool
{
return $this->release_at !== null;
}
/**
* 获取此商品的可售库存
*
* @return int
*/
public function getSaleableStockAttribute(): int
{
if ($this->isOnline()) {
return $this->attributes['stock'];
}
return 0;
}
/**
* 此商品的赠品
*
* @return void
*/
public function gifts()
{
return $this->hasMany(ProductGift::class, 'sku_id');
}
}