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){ /** @var static $userCoupon */ $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 scopeFilterExpired(Query $query,$notExpire=true){ $time = date('Y-m-d H:i:s'); if(!is_null($notExpire)) { if ($notExpire) { $query->where('time_start', '<', $time)->where('time_end', '>', $time); } else { $query->where('time_end', '<', $time)->where('is_use', 0); } } } public function scopeFilterUse(Query $query,$used=1){ $query->where('is_use',$used); } public function needMax(){ return $this->getAttr('type')==Coupon::T_FULL; } public function checkCanUse($amount, $goods_id){ $couponGoods=$this->bindGoods()->column('goods_id'); if(empty($couponGoods)){ $couponGoods[]=$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']); } public static function makeUse($id,$use){ $coupon=self::where('id',$id)->find(); if($coupon){ $coupon['is_use']=$use; $coupon->save(); } } }