UserCoupon.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. 'name'=>$coupon['name'],
  27. 'type'=>$coupon['type'],
  28. 'amount'=>$coupon['amount'],
  29. 'amount_full'=>$coupon['amount_full']??null,
  30. 'time_start'=>$coupon['time_start'],
  31. 'time_end'=>$coupon['time_end'],
  32. ]);
  33. $goods_ids=$coupon->bindGoods()->column('goods_id');
  34. $arr=[];
  35. foreach ($goods_ids as $goods_id){
  36. $arr[]=[
  37. 'goods_id'=>$goods_id,
  38. ];
  39. }
  40. $userCoupon->bindGoods()->saveAll($arr);
  41. }
  42. public function scopeCanUse(Query $query){
  43. $time=date('Y-m-d H:i:s');
  44. $query->where('time_start','<',$time)
  45. ->where('is_use',0)
  46. ->where('time_end','>',$time);
  47. }
  48. public function needMax(){
  49. return $this->getAttr('type')==Coupon::T_FULL;
  50. }
  51. public function canUse($amount,$goods_id){
  52. $couponGoods=$this->bindGoods()->column('goods_id');
  53. $time=date('Y-m-d H:i:s');
  54. if(
  55. (($this['type']==Coupon::T_FULL && $amount>=$this['amount_full'])||
  56. ($this['type']==Coupon::T_WU && $amount>$this['amount'])) &&
  57. in_array($goods_id,$couponGoods) &&
  58. $this['is_use']==0 &&
  59. $this['time_start']<$time && $this['time_end']>$time
  60. ){
  61. return true;
  62. }
  63. return false;
  64. }
  65. public function setUse(){
  66. $this['is_use']=1;
  67. $this->save();
  68. }
  69. public function getNoAttr($id,$model){
  70. return sprintf('%03d',$model['id']);
  71. }
  72. public function getIsExpireAttr($_,$model){
  73. return time()>strtotime($model['time_end']);
  74. }
  75. }