| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace addons\Scratch\common\models;
- use addons\Coupon\common\models\AddonsCoupon;
- use addons\Scratch\common\enums\ScratchEnum;
- use Yii;
- /**
- * Class ScratchUserModel
- * @package addons\Scratch\common\models
- */
- class ScratchCouponModel extends AddonsCoupon
- {
- /**
- * @param $num integer 修改的数量
- * @param $type string 增加add|减少sub
- * @param null|integer $id 优惠券ID
- * @return Coupon|null
- * @throws Exception
- */
- public function updateCount($num, $type, $id = null)
- {
- if ($id) {
- $coupon = self::findOne(['id' => $id, 'status' => [ScratchEnum::DISABLED, ScratchEnum::ENABLED]]);
- } else {
- $coupon = $this;
- }
- if (!$coupon || !$coupon->id) {
- throw new \ErrorException('错误的优惠券信息');
- }
- if ($coupon->total_count == -1) {
- return $coupon;
- }
- if ($type === 'add') {
- $coupon->total_count += $num;
- } elseif ($type === 'sub') {
- if ($coupon->total_count < $num) {
- throw new \ErrorException('优惠券库存不足');
- }
- $coupon->total_count -= $num;
- } else {
- throw new \ErrorException('错误的$type');
- }
- if ($coupon->save()) {
- return $coupon;
- } else {
- throw new \ErrorException($coupon->getErrorMessage());
- }
- }
- /**
- * @param $id
- * @param string $select
- * @return array|\yii\db\ActiveRecord|null
- * @throws \ErrorException
- */
- public static function getData($id, $select = '*')
- {
- try {
- $data = self::find()
- ->where([
- 'id' => $id,
- 'status' => [ScratchEnum::ENABLED, ScratchEnum::DISABLED],
- ])
- ->select($select)
- ->asArray()
- ->one();
- return $data;
- } catch (\Exception $exception) {
- throw new \ErrorException($exception->getMessage());
- }
- }
- }
|