Coupon.php 1.8 KB
<?php

namespace app\common\model;

use think\Model;

class Coupon extends Model
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $append = [
        'rule',
    ];

    /**
     * 优惠券状态
     */
    public function getStatusAttr($value,$data)
    {
        $now_time = time();
        $soon_expire_time = $now_time + 86400 * 3;
        if($data['expiretime'] > $soon_expire_time){
            return 'normal';
        }
        if($data['expiretime'] > $now_time && $data['expiretime'] <= $soon_expire_time){
            return 'soon_expire';
        }
        if($data['expiretime'] < $now_time){
            return 'expired';
        }
    }

    /**
     * 优惠券使用规则
     */
    public function getRuleAttr($value,$data)
    {
        if(empty($data['category_ids'])){
            return '全场通用';
        }
        $category_name_arr = Category::where('id','in',$data['category_ids'])->column('name');
        if(!empty($category_name_arr)){
            return implode('、', $category_name_arr).'品类';
        }
        return '优惠券不可用';
    }

    /**
     * 优惠券列表
     */
    public static function couponList($user){
        $user_id = !$user ? 0 : $user['id'];
        return self::alias('c')
            ->join('user_coupon uc','uc.coupon_id = c.id and uc.user_id = '.$user_id,'left')
            ->where('c.expiretime','>',time())
            ->field("
                c.id,
                c.coupon_name,
                c.coupon_price,
                c.limit_price,
                from_unixtime(c.expiretime,'%Y-%m-%d') expiretime,
                if(uc.coupon_id > 0,'1','0') isreceive,
                category_ids
            ")
            ->group('c.id')
            ->order('c.expiretime asc')
            ->select();
    }
}