最近我遇到了一个有趣的情况。我有2个模型:帐户(id,用户名,密码)和Post(id, account_id, title,…)我在维基上创建了表单。一切正常。但我的问题是帐户->用户名必须是唯一的)))因此,我决定在模型Account中添加验证规则:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
---
array('username', 'checkForUnique'),
---
);
}
public function checkForUnique($attribute, $params)
{
$model = $this->findByAttributes(array("username" => $this->$attribute));
if ($model) {
// I do not know what to do
}
}
我的问题是:如何检查用户名,如果用户名已经存在,将模型帐户的实例更改为$model
对于验证唯一值,您可以添加以下规则:
public function rules()
{
return array(
...
array('username', 'unique'),
...
);
}
你应该在控制器中检查模型,如果有相同用户名的模型已经存在,那么使用它,如果没有-那么使用新实例:
你的控制器:
...
$model = $this->findByAttributes(array("username" => $_POST["Account"]["username"]));
if(is_null($model)){
$model = new Account();
}
...
然后在$model中填写数据,验证并保存