CouponModel.php 2.4 KB
<?php
/**
 * Created by PhpStorm.
 * User: yhbr
 * Date: 2018/9/5
 * Time: 15:03
 */
namespace app\coupons\model;
use think\Model;
use think\Db;

class CouponModel extends Model
{
    /**
     * 个人中心优惠券列表
     * @param null $status
     * @param $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllDiscountCouponByUniqueIdAndByStatus($status = null, $user_id)
    {
        if ($status == null) {
            $status = 1;
        }
        $map['status'] = array('eq', $status);
        $map['user_id'] = array('eq', $user_id);
        $res = Db::name('discount_coupon')->field('id,reduce,discount_coupon_name,deadline')->where($map)->select()->toArray();
        foreach ($res as $key => $item) {
            $item['deadline'] = date('Y-m-d', $item['deadline']);
            $res[$key] = $item;
        }
        return $res;
    }

    /**
     * 根据金额获取符合条件的满减优惠券
     * @param $activity_id
     * @param null $schedule_id
     * @param $num
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderCoupon($activity_id, $schedule_id = null, $num, $userId)
    {
        $info = Db::name('activity')->field('is_down_payment,down_price')->where(['id' => $activity_id])->find();
        //如果有定金,则按照定金计算满减
        if ($info['is_down_payment'] == 1) {
            $overflow = $info['down_price'] * $num;
        } //如果没有定金,则直接按照选中的活动批次价格计算满减
        else {
            $price = Db::name('activity_schedule')->where(['activity_id' => $activity_id, 'id' => $schedule_id])->value('price');
            $overflow = $price * $num;
        }
        $map = [
            'user_id' => ['eq', $userId],
            'overflow' => ['elt', $overflow],
            'deadline' => ['gt', time()],
            'status' => ['eq', 1]
        ];
        $coupons = Db::name('discount_coupon')->field('id as discount_coupon_id,discount_coupon_name,reduce')->where($map)->select()->toArray();
        return (empty($coupons)) ? null : $coupons;
    }

}