我希望我的应用程序检测用户名何时被使用并更改它。事实上,当用户注册自己时,他输入了他的姓氏和名字,用户名是 lastName.firstName。如何检测用户名已被使用以及如何更改它(例如添加一个数字)?
谢谢。
我希望我的应用程序检测用户名何时被使用并更改它。事实上,当用户注册自己时,他输入了他的姓氏和名字,用户名是 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
函数以在保存前检测和更改用户名。