UserCoupon.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\common\model;
  3. use think\db\Query;
  4. use think\Model;
  5. class UserCoupon extends Model
  6. {
  7. protected $autoWriteTimestamp=true;
  8. protected $updateTime=null;
  9. protected $append=[
  10. 'no',
  11. 'is_expire',
  12. ];
  13. public function bindGoods(){
  14. return $this->hasMany(UserCouponGoods::class,'coupon_id');
  15. }
  16. protected static function init()
  17. {
  18. self::beforeWrite(function (self $coupon){
  19. if($coupon['type']==2){
  20. unset($coupon['amount_full']);
  21. }
  22. });
  23. }
  24. public static function toUser(User $user,Coupon $coupon){
  25. $userCoupon=$user->coupon()->save([
  26. 'type'=>$coupon['type'],
  27. 'amount'=>$coupon['amount'],
  28. 'amount_full'=>$coupon['amount_full']??null,
  29. 'time_start'=>$coupon['time_start'],
  30. 'time_end'=>$coupon['time_end'],
  31. ]);
  32. $goods_ids=$coupon->bindGoods()->column('goods_id');
  33. $arr=[];
  34. foreach ($goods_ids as $goods_id){
  35. $arr[]=[
  36. 'goods_id'=>$goods_id,
  37. ];
  38. }
  39. $userCoupon->bindGoods()->saveAll($arr);
  40. }
  41. public function scopeCanUse(Query $query){
  42. $time=date('Y-m-d H:i:s');
  43. $query->where('time_start','<',$time)
  44. ->where('is_use',0)
  45. ->where('time_end','>',$time);
  46. }
  47. public function needMax(){
  48. return $this->getAttr('type')==Coupon::T_FULL;
  49. }
  50. public function canUse($amount,$goods_id){
  51. $couponGoods=$this->bindGoods()->column('goods_id');
  52. $time=date('Y-m-d H:i:s');
  53. if(
  54. (($this['type']==Coupon::T_FULL && $amount>=$this['amount_full'])||
  55. ($this['type']==Coupon::T_WU && $amount>$this['amount'])) &&
  56. in_array($goods_id,$couponGoods) &&
  57. $this['is_use']==0 &&
  58. $this['time_start']<$time && $this['time_end']>$time
  59. ){
  60. return true;
  61. }
  62. return false;
  63. }
  64. public function setUse(){
  65. $this['is_use']=1;
  66. $this->save();
  67. }
  68. public function getNoAttr($id,$model){
  69. return sprintf('%03d',$model['id']);
  70. }
  71. public function getIsExpireAttr($_,$model){
  72. return time()>strtotime($model['time_end']);
  73. }
  74. }