ScratchCouponModel.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace addons\Scratch\common\models;
  3. use addons\Coupon\common\models\AddonsCoupon;
  4. use addons\Scratch\common\enums\ScratchEnum;
  5. use Yii;
  6. /**
  7. * Class ScratchUserModel
  8. * @package addons\Scratch\common\models
  9. */
  10. class ScratchCouponModel extends AddonsCoupon
  11. {
  12. /**
  13. * @param $num integer 修改的数量
  14. * @param $type string 增加add|减少sub
  15. * @param null|integer $id 优惠券ID
  16. * @return Coupon|null
  17. * @throws Exception
  18. */
  19. public function updateCount($num, $type, $id = null)
  20. {
  21. if ($id) {
  22. $coupon = self::findOne(['id' => $id, 'status' => [ScratchEnum::DISABLED, ScratchEnum::ENABLED]]);
  23. } else {
  24. $coupon = $this;
  25. }
  26. if (!$coupon || !$coupon->id) {
  27. throw new \ErrorException('错误的优惠券信息');
  28. }
  29. if ($coupon->total_count == -1) {
  30. return $coupon;
  31. }
  32. if ($type === 'add') {
  33. $coupon->total_count += $num;
  34. } elseif ($type === 'sub') {
  35. if ($coupon->total_count < $num) {
  36. throw new \ErrorException('优惠券库存不足');
  37. }
  38. $coupon->total_count -= $num;
  39. } else {
  40. throw new \ErrorException('错误的$type');
  41. }
  42. if ($coupon->save()) {
  43. return $coupon;
  44. } else {
  45. throw new \ErrorException($coupon->getErrorMessage());
  46. }
  47. }
  48. /**
  49. * @param $id
  50. * @param string $select
  51. * @return array|\yii\db\ActiveRecord|null
  52. * @throws \ErrorException
  53. */
  54. public static function getData($id, $select = '*')
  55. {
  56. try {
  57. $data = self::find()
  58. ->where([
  59. 'id' => $id,
  60. 'status' => [ScratchEnum::ENABLED, ScratchEnum::DISABLED],
  61. ])
  62. ->select($select)
  63. ->asArray()
  64. ->one();
  65. return $data;
  66. } catch (\Exception $exception) {
  67. throw new \ErrorException($exception->getMessage());
  68. }
  69. }
  70. }