ShopPromotionItem.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Module\Shop\Models;
  3. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  4. use UCore\ModelCore;
  5. /**
  6. * 商店促销商品关联模型
  7. *
  8. * field start
  9. * @property int $id 关联ID,主键
  10. * @property int $promotion_id 促销ID,外键关联kku_shop_promotions表
  11. * @property int $shop_item_id 商品ID,外键关联kku_shop_items表
  12. * @property int $custom_discount_value 自定义折扣值(可为空,优先于促销活动的折扣值)
  13. * @property \Carbon\Carbon $created_at 创建时间
  14. * @property \Carbon\Carbon $updated_at 更新时间
  15. * field end
  16. */
  17. class ShopPromotionItem extends ModelCore
  18. {
  19. /**
  20. * 与模型关联的表名
  21. *
  22. * @var string
  23. */
  24. protected $table = 'shop_promotion_items';
  25. /**
  26. * 可批量赋值的属性
  27. *
  28. * @var array
  29. */
  30. protected $fillable = [
  31. 'promotion_id',
  32. 'shop_item_id',
  33. 'custom_discount_value',
  34. ];
  35. /**
  36. * 获取关联的促销活动
  37. *
  38. * @return BelongsTo
  39. */
  40. public function promotion(): BelongsTo
  41. {
  42. return $this->belongsTo(ShopPromotion::class, 'promotion_id');
  43. }
  44. /**
  45. * 获取关联的商品
  46. *
  47. * @return BelongsTo
  48. */
  49. public function shopItem(): BelongsTo
  50. {
  51. return $this->belongsTo(ShopItem::class, 'shop_item_id');
  52. }
  53. /**
  54. * 计算折扣后的价格
  55. *
  56. * @return int|null 折扣后的价格,如果商品或促销活动不存在则返回null
  57. */
  58. public function getDiscountedPrice(): ?int
  59. {
  60. $shopItem = $this->shopItem;
  61. $promotion = $this->promotion;
  62. if (!$shopItem || !$promotion || !$promotion->isValid()) {
  63. return null;
  64. }
  65. return $promotion->calculateDiscountedPrice(
  66. $shopItem->price,
  67. $this->custom_discount_value
  68. );
  69. }
  70. }