Coupon.php 2.6 KB

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