Coupon.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\api\model;
  10. use app\common\model\Coupon as CouponModel;
  11. /**
  12. * 优惠券模型
  13. * Class Coupon
  14. * @package app\api\model
  15. */
  16. class Coupon extends CouponModel
  17. {
  18. /**
  19. * 隐藏字段
  20. * @var array
  21. */
  22. protected $hidden = [
  23. 'receive_num',
  24. 'is_delete',
  25. 'create_time',
  26. 'update_time',
  27. ];
  28. /**
  29. * 获取优惠券列表
  30. * @param bool $user
  31. * @param null $limit
  32. * @param bool $only_receive
  33. * @return false|\PDOStatement|string|\think\Collection
  34. * @throws \think\db\exception\DataNotFoundException
  35. * @throws \think\db\exception\ModelNotFoundException
  36. * @throws \think\exception\DbException
  37. */
  38. public function getList($user = false, $limit = null, $only_receive = false)
  39. {
  40. // 构造查询条件
  41. $this->where('is_delete', '=', 0);
  42. // 只显示可领取(未过期,未发完)的优惠券
  43. if ($only_receive) {
  44. $this->where(' IF ( `total_num` > - 1, `receive_num` < `total_num`, 1 = 1 )')
  45. ->where('IF ( `expire_type` = 20, (`end_time` + 86400) >= ' . time() . ', 1 = 1 )');
  46. }
  47. // 优惠券列表
  48. $couponList = $this->order(['sort' => 'asc', 'create_time' => 'desc'])->limit($limit)->select();
  49. // 获取用户已领取的优惠券
  50. if ($user !== false) {
  51. $UserCouponModel = new UserCoupon;
  52. $userCouponIds = $UserCouponModel->getUserCouponIds($user['user_id']);
  53. foreach ($couponList as $key => $item) {
  54. $couponList[$key]['is_receive'] = in_array($item['coupon_id'], $userCouponIds);
  55. }
  56. }
  57. return $couponList;
  58. }
  59. /**
  60. * 验证优惠券是否可领取
  61. * @return bool
  62. */
  63. public function checkReceive()
  64. {
  65. if ($this['total_num'] > -1 && $this['receive_num'] >= $this['total_num']) {
  66. $this->error = '优惠券已发完';
  67. return false;
  68. }
  69. if ($this['expire_type'] == 20 && ($this->getData('end_time') + 86400) < time()) {
  70. $this->error = '优惠券已过期';
  71. return false;
  72. }
  73. return true;
  74. }
  75. /**
  76. * 累计已领取数量
  77. * @return int|true
  78. * @throws \think\Exception
  79. */
  80. public function setIncReceiveNum()
  81. {
  82. return $this->setInc('receive_num');
  83. }
  84. }