Coupon.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\index\model;
  13. use app\index\model\UserCoupon;
  14. use app\index\service\User as UserService;
  15. use app\common\model\Coupon as CouponModel;
  16. use cores\exception\BaseException;
  17. /**
  18. * 优惠券模型
  19. * Class Coupon
  20. * @package app\api\model
  21. */
  22. class Coupon extends CouponModel
  23. {
  24. /**
  25. * 隐藏字段
  26. * @var array
  27. */
  28. protected $hidden = [
  29. 'receive_num',
  30. 'is_delete',
  31. 'create_time',
  32. 'update_time',
  33. ];
  34. /**
  35. * 获取优惠券列表
  36. * @param int|null $limit 获取的数量
  37. * @param bool $onlyReceive 只显示可领取
  38. * @return mixed
  39. * @throws BaseException
  40. * @throws \think\db\exception\DataNotFoundException
  41. * @throws \think\db\exception\DbException
  42. * @throws \think\db\exception\ModelNotFoundException
  43. */
  44. public function getList(int $limit = null, bool $onlyReceive = false)
  45. {
  46. // 查询构造器
  47. $query = $this->getNewQuery();
  48. // 只显示可领取(未过期,未发完)的优惠券
  49. if ($onlyReceive) {
  50. $query->where('IF ( `total_num` > - 1, `receive_num` < `total_num`, 1 = 1 )')
  51. ->where('IF ( `expire_type` = 20, (`end_time` + 86400) >= ' . time() . ', 1 = 1 )');
  52. }
  53. // 查询数量
  54. $limit > 0 && $query->limit($limit);
  55. // 优惠券列表
  56. $couponList = $query->where('status', '=', 1)
  57. ->where('is_delete', '=', 0)
  58. ->order(['sort', 'create_time' => 'desc'])
  59. ->select();
  60. // 获取用户已领取的优惠券
  61. return $this->setIsReceive($couponList);
  62. }
  63. /**
  64. * 获取用户已领取的优惠券
  65. * @param mixed $couponList
  66. * @return mixed
  67. * @throws BaseException
  68. */
  69. private function setIsReceive($couponList)
  70. {
  71. // 获取用户已领取的优惠券
  72. $userInfo = UserService::getCurrentLoginUser();
  73. if ($userInfo !== false) {
  74. $UserCouponModel = new UserCoupon;
  75. $userCouponIds = $UserCouponModel->getUserCouponIds($userInfo['user_id']);
  76. foreach ($couponList as $key => $item) {
  77. $couponList[$key]['is_receive'] = in_array($item['coupon_id'], $userCouponIds);
  78. }
  79. }
  80. return $couponList;
  81. }
  82. }