我想让我的应用程序检测用户名何时已被占用并更改。事实上,当用户注册时,他会输入自己的姓氏和名字,用户名是lastName.firstName。我如何检测用户名已被占用以及如何更改(例如添加数字)?
谢谢。
所以你应该覆盖beforeValidate()
函数,下面是我的示例代码:
/**
* @inheritdoc
*/
public function beforeValidate()
{
/** your code here **/
$isExist = static::find()->where(['username' => $this->username])->count();
if($isExist){
//Count total rows with the similar username
$total = static::find()->where(['LIKE','username', "{$this->username}%"])->count();
//We will add $total + 1 to the username so we have new unique username
$this->username .= '-' . ($total+1);
}
return parent::beforeValidate();
}
您使用的用户模块是什么?是dektrium/yii2-user
模块吗?
我们可以在保存之前覆盖用户模型类和beforeValidate
函数来检测和更改用户名。