UserCoupon.php 2.1 KB
<?php

namespace app\common\model;

use think\Model;

class UserCoupon extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    /**
     * 优惠券
     */
    public function coupon()
    {
        return $this->belongsTo('Coupon');
    }

    /**
     * 优惠券
     */
    public function getStatusAttr($value,$data)
    {
        return $data['status'] == '2' ? 'used' : $this['coupon']['status'];
    }

    /**
     * 优惠券列表
     */
    public static function couponList($user,$status='all'){
        // 筛选条件
        $filter = [];
        $now_time = time();
        $soon_expire_time = $now_time + 86400 * 3;
        // 优惠券状态
        switch ($status) {
            case 'all':
                break;
            case 'normal':
                $filter['uc.status'] = '1';
                $filter['c.expiretime'] = ['>',$soon_expire_time];
                break;
            case 'soon_expire';
                $filter = "uc.status = '1' and c.expiretime > {$now_time} and c.expiretime <= {$soon_expire_time}";
                break;
            case 'expired';
                $filter['uc.status'] = '1';
                $filter['c.expiretime'] = ['<',$now_time];
                break;
            case 'used';
                $filter['uc.status'] = '2';
                break;
        }
        $list = self::alias('uc')
            ->join('coupon c','c.id = uc.coupon_id')
            ->with('coupon')
            ->where('uc.user_id',$user['id'])
            ->where($filter)
            ->field("
                uc.id,
                uc.coupon_id,
                uc.status,
                from_unixtime(c.expiretime,'%Y-%m-%d') expiretime
            ")
            ->order('c.expiretime asc')
            ->select();
        foreach($list as $v){
            $v->visible(['id','status','expiretime','coupon']);
            $v->getRelation('coupon')->visible(['id','coupon_name','coupon_price','limit_price','category_ids','rule']);
        }
        return $list;
    }
}