0, 'stock' => 0, 'sales' => 0, ]; /** * @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'); } /** * 此商品所属的 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'); } /** * 此商品的赠品 */ public function gifts() { return $this->hasMany(ProductGift::class, 'sku_id'); } /** * 此商品的购买须知 */ public function buynote() { return $this->belongsTo(ProductBuynote::class, 'buynote_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; } }