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

181 lines
3.5 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;
/**
* @var array
*/
protected $attributes = [
'weight' => 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;
}
/**
* 根据用户来获取商品的真实价格
*
* @param \App\Models\User $user
* @return int
*/
public function getRealPrice(User $user): int
{
if (! is_null($this->vip_price) && $user->isVip()) {
return $this->vip_price;
}
return $this->sell_price;
}
/**
* 获取此商品的可售库存
*
* @return int
*/
public function getSaleableStockAttribute(): int
{
if ($this->isOnline()) {
return $this->attributes['stock'];
}
return 0;
}
/**
* 获取商品售价
*
* @return string
*/
public function getSellPriceFormatAttribute()
{
return bcdiv($this->attributes['sell_price'], 100, 2);
}
/**
* 获取商品会员价
*
* @return string
*/
public function getVipPriceFormatAttribute()
{
if (is_null($price = $this->attributes['vip_price'])) {
return '';
}
return bcdiv($price, 100, 2);
}
}