| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace common\models\user;
- use common\enums\StatusEnum;
- use common\helpers\StringHelper;
- use Yii;
- /**
- * This is the model class for table "{{%user_invite_code}}".
- *
- * @property int $id ID
- * @property int $mall_id 商城ID
- * @property int $user_id 用户ID
- * @property string $code 邀请码[二位前缀+六位随机字符(含数字和字母)]
- * @property int $status 状态[-1删除; 0禁用; 1正常]
- * @property int $created_at 创建时间
- * @property int $updated_at 更新时间
- * @property User $user
- *
- */
- class UserInviteCode extends \common\models\base\BaseActiveRecord
- {
- const CODE_PREFIX = 'HN';
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%user_invite_code}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['user_id', 'mall_id', 'status', 'created_at', 'updated_at'], 'integer'],
- [['code'], 'string', 'max' => 10],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => '商城ID',
- 'user_id' => '用户ID',
- 'code' => '邀请码[二位前缀+六位随机字符(含数字和字母)]',
- 'status' => '状态[-1删除; 0禁用; 1正常]',
- 'created_at' => '创建时间',
- 'updated_at' => '更新时间',
- ];
- }
- public function getUser()
- {
- return $this->hasOne(User::class, ['id' => 'user_id']);
- }
- public static function setData(array $params)
- {
- try {
- $model = self::findOne(['user_id' => $params['user_id'], 'mall_id' => $params['mall_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
- if (empty($model)) {
- $model = new self();
- $model->loadDefaultValues();
- $model->code = self::createUserCode($params['mall_id'], 0);
- }
- if (!$model->load($params, '') || !$model->save()) throw new \Exception($model->getErrorMessage());
- return $model;
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- public static function createUserCode($mall_id, $retry = 0)
- {
- $code = self::CODE_PREFIX . StringHelper::random(6, true);
- $exist = self::findOne(['mall_id' => $mall_id, 'code' => $code]);
- if (empty($exist)) return $code;
- $retry++;
- if ($retry >= 3) throw new \Exception('用户邀请码生成失败code:'.$code);
- return self::createUserCode($mall_id, $retry);
- }
- }
|