Coupon.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php namespace App\Models;
  2. use App\Facades\Servers\Redis\Redis;
  3. use App\Facades\Servers\Redis\RedisLock;
  4. use App\Models\Traits\Coupon\GrantType;
  5. use Illuminate\Database\Eloquent\Factories\HasFactory;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Support\Carbon;
  8. /**
  9. * 优惠券模型
  10. *
  11. */
  12. class Coupon extends Model
  13. {
  14. use HasFactory,GrantType;
  15. // 与模型关联的表名
  16. protected $table = 'coupon';
  17. // 是否主动维护时间戳
  18. public $timestamps = false;
  19. // 定义时间戳字段名
  20. // const CREATED_AT = 'insert_time';
  21. // const UPDATED_AT = 'update_time';
  22. /**
  23. * 添加数据
  24. *
  25. */
  26. public function add($data)
  27. {
  28. // 时间
  29. $data['insert_time'] = time();
  30. $data['update_time'] = time();
  31. // 写入数据表
  32. $id = $this->query()->insertGetId($data);
  33. // 返回结果
  34. return $id;
  35. }
  36. /**
  37. * 添加数据
  38. *
  39. */
  40. public function edit($id,$data)
  41. {
  42. // 更新时间
  43. $data['update_time'] = time();
  44. // 写入数据表
  45. $result = $this->query()->where(['id'=>$id])->update($data);
  46. // 返回结果
  47. return $result;
  48. }
  49. /**
  50. * 编码转id
  51. *
  52. * @param string $code 编码
  53. *
  54. */
  55. public function codeToId($code){
  56. return intval(str_ireplace('klyhq','',$code));
  57. }
  58. /**
  59. * id转编码
  60. *
  61. * @param int $id 编码
  62. *
  63. */
  64. public function idToCode($id){
  65. return 'klyhq'. str_pad($id, 9, '0', STR_PAD_LEFT);
  66. }
  67. /**
  68. * 优惠券过期时间
  69. *
  70. * @param int $expTime 过期时间
  71. *
  72. */
  73. public function getExpTime($expTime){
  74. // 如果存在过期时间,且小于1000,表示这是一个领取后n天的,按天数返回
  75. if ( $expTime && $expTime < 1000 ) return Carbon::now()->addDays($expTime)->endOfDay()->getTimestamp();
  76. // 返回时间戳
  77. return $expTime;
  78. }
  79. /**
  80. * 过期状态设置
  81. *
  82. */
  83. public function setStatusByExpire(){
  84. // 上锁
  85. if(RedisLock::lock('coupon::set::status::by::expire',1,30)){
  86. // 修改
  87. $result = $this->query()->where([['status','=',0],['end_time','>',0],['end_time','<=',time()]])->update(['status'=>3,'update_time'=>time()]);
  88. // 不管成功失败,都解锁
  89. RedisLock::unlock('coupon::set::status::by::expire',1);
  90. // 返回结果
  91. return $result;
  92. }
  93. }
  94. /**
  95. * 获取优惠券信息
  96. *
  97. */
  98. public function getOne($id,$field=''){
  99. // 返回结果
  100. $result = $this->query()->find($id);
  101. // 返回结果
  102. $result = $result ? $result->toArray() : [];
  103. // 返回值
  104. return empty($field) ? $result : ( isset($result[$field]) ? $result[$field] : null);
  105. }
  106. }