UserInviteCode.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace common\models\user;
  3. use common\enums\StatusEnum;
  4. use common\helpers\StringHelper;
  5. use Yii;
  6. /**
  7. * This is the model class for table "{{%user_invite_code}}".
  8. *
  9. * @property int $id ID
  10. * @property int $mall_id 商城ID
  11. * @property int $user_id 用户ID
  12. * @property string $code 邀请码[二位前缀+六位随机字符(含数字和字母)]
  13. * @property int $status 状态[-1删除; 0禁用; 1正常]
  14. * @property int $created_at 创建时间
  15. * @property int $updated_at 更新时间
  16. * @property User $user
  17. *
  18. */
  19. class UserInviteCode extends \common\models\base\BaseActiveRecord
  20. {
  21. const CODE_PREFIX = 'HN';
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public static function tableName()
  26. {
  27. return '{{%user_invite_code}}';
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function rules()
  33. {
  34. return [
  35. [['user_id', 'mall_id', 'status', 'created_at', 'updated_at'], 'integer'],
  36. [['code'], 'string', 'max' => 10],
  37. ];
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function attributeLabels()
  43. {
  44. return [
  45. 'id' => 'ID',
  46. 'mall_id' => '商城ID',
  47. 'user_id' => '用户ID',
  48. 'code' => '邀请码[二位前缀+六位随机字符(含数字和字母)]',
  49. 'status' => '状态[-1删除; 0禁用; 1正常]',
  50. 'created_at' => '创建时间',
  51. 'updated_at' => '更新时间',
  52. ];
  53. }
  54. public function getUser()
  55. {
  56. return $this->hasOne(User::class, ['id' => 'user_id']);
  57. }
  58. public static function setData(array $params)
  59. {
  60. try {
  61. $model = self::findOne(['user_id' => $params['user_id'], 'mall_id' => $params['mall_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  62. if (empty($model)) {
  63. $model = new self();
  64. $model->loadDefaultValues();
  65. $model->code = self::createUserCode($params['mall_id'], 0);
  66. }
  67. if (!$model->load($params, '') || !$model->save()) throw new \Exception($model->getErrorMessage());
  68. return $model;
  69. } catch (\Exception $e) {
  70. self::$static_error = $e->getMessage();
  71. return false;
  72. }
  73. }
  74. public static function createUserCode($mall_id, $retry = 0)
  75. {
  76. $code = self::CODE_PREFIX . StringHelper::random(6, true);
  77. $exist = self::findOne(['mall_id' => $mall_id, 'code' => $code]);
  78. if (empty($exist)) return $code;
  79. $retry++;
  80. if ($retry >= 3) throw new \Exception('用户邀请码生成失败code:'.$code);
  81. return self::createUserCode($mall_id, $retry);
  82. }
  83. }