123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- <?php namespace App\Models;
- use App\Facades\Servers\Redis\Redis;
- use App\Facades\Servers\Redis\RedisLock;
- use App\Models\Traits\Coupon\GrantType;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Carbon;
- /**
- * 优惠券模型
- *
- */
- class Coupon extends Model
- {
- use HasFactory,GrantType;
- // 与模型关联的表名
- protected $table = 'coupon';
- // 是否主动维护时间戳
- public $timestamps = false;
- // 定义时间戳字段名
- // const CREATED_AT = 'insert_time';
- // const UPDATED_AT = 'update_time';
- /**
- * 添加数据
- *
- */
- public function add($data)
- {
- // 时间
- $data['insert_time'] = time();
- $data['update_time'] = time();
- // 写入数据表
- $id = $this->query()->insertGetId($data);
- // 返回结果
- return $id;
- }
- /**
- * 添加数据
- *
- */
- public function edit($id,$data)
- {
- // 更新时间
- $data['update_time'] = time();
- // 写入数据表
- $result = $this->query()->where(['id'=>$id])->update($data);
- // 返回结果
- return $result;
- }
- /**
- * 编码转id
- *
- * @param string $code 编码
- *
- */
- public function codeToId($code){
- return intval(str_ireplace('klyhq','',$code));
- }
-
- /**
- * id转编码
- *
- * @param int $id 编码
- *
- */
- public function idToCode($id){
- return 'klyhq'. str_pad($id, 9, '0', STR_PAD_LEFT);
- }
- /**
- * 优惠券过期时间
- *
- * @param int $expTime 过期时间
- *
- */
- public function getExpTime($expTime){
- // 如果存在过期时间,且小于1000,表示这是一个领取后n天的,按天数返回
- if ( $expTime && $expTime < 1000 ) return Carbon::now()->addDays($expTime)->endOfDay()->getTimestamp();
- // 返回时间戳
- return $expTime;
- }
- /**
- * 过期状态设置
- *
- */
- public function setStatusByExpire(){
- // 上锁
- if(RedisLock::lock('coupon::set::status::by::expire',1,30)){
- // 修改
- $result = $this->query()->where([['status','=',0],['end_time','>',0],['end_time','<=',time()]])->update(['status'=>3,'update_time'=>time()]);
- // 不管成功失败,都解锁
- RedisLock::unlock('coupon::set::status::by::expire',1);
- // 返回结果
- return $result;
- }
- }
- /**
- * 获取优惠券信息
- *
- */
- public function getOne($id,$field=''){
- // 返回结果
- $result = $this->query()->find($id);
- // 返回结果
- $result = $result ? $result->toArray() : [];
- // 返回值
- return empty($field) ? $result : ( isset($result[$field]) ? $result[$field] : null);
- }
- }
|