AddonsCouponGoodsRelate.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\Coupon\common\models;
  3. use common\models\base\BaseActiveRecord;
  4. use PHPUnit\Util\Exception;
  5. use Yii;
  6. /**
  7. * This is the model class for table "qimall_addons_coupon_goods_relate".
  8. *
  9. * @property int $id
  10. * @property int $coupon_id 优惠券id
  11. * @property int $goods_id 商品id
  12. * @property int $created_at 创建时间
  13. * @property int $updated_at 修改时间
  14. */
  15. class AddonsCouponGoodsRelate extends BaseActiveRecord
  16. {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public static function tableName()
  21. {
  22. return '{{%addons_coupon_goods_relate}}';
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function rules()
  28. {
  29. return [
  30. [['coupon_id', 'goods_id'], 'required'],
  31. [['coupon_id', 'goods_id', 'created_at', 'updated_at'], 'integer'],
  32. ];
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function attributeLabels()
  38. {
  39. return [
  40. 'id' => 'ID',
  41. 'coupon_id' => '优惠券id',
  42. 'goods_id' => '商品id',
  43. 'created_at' => '创建时间',
  44. 'updated_at' => '修改时间',
  45. ];
  46. }
  47. /**
  48. * 保存数据
  49. * @param $coupon_id
  50. * @param $goods_id
  51. * @return bool
  52. * @throws \yii\db\Exception
  53. */
  54. public static function setData($coupon_id, $goods_id)
  55. {
  56. try {
  57. if ($coupon_id && $goods_id) {
  58. $count = self::deleteAll([
  59. 'and',
  60. ['coupon_id' => $coupon_id],
  61. ['not in', 'goods_id', $goods_id]
  62. ]);
  63. $exist_goods_ids = self::find()->select('goods_id')
  64. ->where(['goods_id' => $goods_id,'coupon_id' => $coupon_id])
  65. ->column();
  66. $insert = [];
  67. $now = time();
  68. foreach ($goods_id as $key => $id) {
  69. if (in_array($id, $exist_goods_ids)) continue;
  70. $insert[] = [$coupon_id, $id, $now, $now];
  71. }
  72. $field = ['coupon_id', 'goods_id', 'created_at', 'updated_at'];
  73. // 批量插入数据
  74. Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $insert)->execute();
  75. }
  76. return true;
  77. } catch (Exception $e) {
  78. self::$static_error = $e->getMessage();
  79. return false;
  80. }
  81. }
  82. }