123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace app\common\model;
- use think\db\Query;
- use think\Model;
- class UserCoupon extends Model
- {
- protected $autoWriteTimestamp=true;
- protected $updateTime=null;
- protected $append=[
- 'no',
- 'is_expire',
- ];
- public function bindGoods(){
- return $this->hasMany(UserCouponGoods::class,'coupon_id');
- }
- protected static function init()
- {
- self::beforeWrite(function (self $coupon){
- if($coupon['type']==2){
- unset($coupon['amount_full']);
- }
- });
- }
- public static function toUser(User $user,Coupon $coupon){
- $userCoupon=$user->coupon()->save([
- 'name'=>$coupon['name'],
- 'type'=>$coupon['type'],
- 'amount'=>$coupon['amount'],
- 'amount_full'=>$coupon['amount_full']??null,
- 'time_start'=>$coupon['time_start'],
- 'time_end'=>$coupon['time_end'],
- ]);
- $goods_ids=$coupon->bindGoods()->column('goods_id');
- $arr=[];
- foreach ($goods_ids as $goods_id){
- $arr[]=[
- 'goods_id'=>$goods_id,
- ];
- }
- $userCoupon->bindGoods()->saveAll($arr);
- }
- public function scopeCanUse(Query $query){
- $time=date('Y-m-d H:i:s');
- $query->where('time_start','<',$time)
- ->where('is_use',0)
- ->where('time_end','>',$time);
- }
- public function needMax(){
- return $this->getAttr('type')==Coupon::T_FULL;
- }
- public function canUse($amount,$goods_id){
- $couponGoods=$this->bindGoods()->column('goods_id');
- $time=date('Y-m-d H:i:s');
- if(
- (($this['type']==Coupon::T_FULL && $amount>=$this['amount_full'])||
- ($this['type']==Coupon::T_WU && $amount>$this['amount'])) &&
- in_array($goods_id,$couponGoods) &&
- $this['is_use']==0 &&
- $this['time_start']<$time && $this['time_end']>$time
- ){
- return true;
- }
- return false;
- }
- public function setUse(){
- $this['is_use']=1;
- $this->save();
- }
- public function getNoAttr($id,$model){
- return sprintf('%03d',$model['id']);
- }
- public function getIsExpireAttr($_,$model){
- return time()>strtotime($model['time_end']);
- }
- }
|