Coupon.php 2.3 KB

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