【问题标题】:yii2 advanced template extend User model and no data savedyii2 高级模板扩展用户模型并且没有保存数据
【发布时间】:2015-08-06 03:59:55
【问题描述】:

我最近刚刚下载了 yii2 高级模板,并在前端模块中创建了新模型,像这样在“common/models”中扩展用户

class UsUser extends User
{

}

class SignupForm extends Model
{      

/**
 * Signs user up.
 *
 * @return User|null the saved model or null if saving fails
 */
public function signup()
{
    if ($this->validate()) {
        $user = new UsUser();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();
        return $user;
    }

    return null;
}

当我注册时,没有错误,只是被重定向到主页,但没有数据插入到数据库中。我没有在我的模型(User 或 UsUser)中使用由 Tal V. 指定的公共属性(Yii2 active record model not saving data)。所以在 UsUser 中只有 @property 注释。

也许我做错了,或者还有其他需要注意的地方,有人可以帮忙指出吗?非常感谢。

【问题讨论】:

  • 如果条件使用 $user->save(false);
  • @Ali 你是对的,我认为这与验证有关,当我按照你所说的那样输入 $user->save(false) 时,它实际上将数据插入到数据库中。如何知道哪个验证失败?我想知道为什么 $this->validate() 无论如何都会返回 true。对不起,我刚下班回家晚了,我应该继续做更多的研究。

标签: activerecord yii2 yii2-advanced-app


【解决方案1】:
class SignupForm extends Model
{

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate())
        {
            $user           = new UsUser();
            $user->username = $this->username;
            $user->email    = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            //IF UsUser MODEL IS VALID THEN SAVE DATA
            if ($user->validate())
            {
                $user->save(false);
                return $user;
            }
            //IF UsUser MODEL IS NOT VALID THEN PRINT THE ERRORS.SO YOU CAN CHECK WHAT ARE THE ERRORS IN MODEL
            else
            {
                echo "<pre>";
                print_r($user->getErrors());
                echo "</pre>";
            }
        }
    }

}

【讨论】:

  • 感谢您的提示,使用它进行调试变得更加容易。发生的情况是我使用 gii 生成 us_user 表,密码的列字段是 varchar (45),Yii 的密码生成器经过哈希处理,将生成 60 个字符,而我的 UsUser 模型上有“max=> 45”规则。无论如何,如果违反规则,我相信 yii 实际上会提示错误,我知道为什么 yii2 没有。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 2016-01-05
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多