ShopPromotionItem.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. * field end
  10. */
  11. class ShopPromotionItem extends ModelCore
  12. {
  13. /**
  14. * 与模型关联的表名
  15. *
  16. * @var string
  17. */
  18. protected $table = 'shop_promotion_items';
  19. /**
  20. * 可批量赋值的属性
  21. *
  22. * @var array
  23. */
  24. protected $fillable = [
  25. 'promotion_id',
  26. 'shop_item_id',
  27. 'custom_discount_value',
  28. ];
  29. /**
  30. * 获取关联的促销活动
  31. *
  32. * @return BelongsTo
  33. */
  34. public function promotion(): BelongsTo
  35. {
  36. return $this->belongsTo(ShopPromotion::class, 'promotion_id');
  37. }
  38. /**
  39. * 获取关联的商品
  40. *
  41. * @return BelongsTo
  42. */
  43. public function shopItem(): BelongsTo
  44. {
  45. return $this->belongsTo(ShopItem::class, 'shop_item_id');
  46. }
  47. /**
  48. * 计算折扣后的价格
  49. *
  50. * @return int|null 折扣后的价格,如果商品或促销活动不存在则返回null
  51. */
  52. public function getDiscountedPrice(): ?int
  53. {
  54. $shopItem = $this->shopItem;
  55. $promotion = $this->promotion;
  56. if (!$shopItem || !$promotion || !$promotion->isValid()) {
  57. return null;
  58. }
  59. return $promotion->calculateDiscountedPrice(
  60. $shopItem->price,
  61. $this->custom_discount_value
  62. );
  63. }
  64. }