【问题标题】:create and update user from active record从活动记录创建和更新用户
【发布时间】:2016-05-19 21:20:17
【问题描述】:

我在扩展 ActiveRecord 类的用户表的后端做了 CRUD。但是在我的表中,我有很多数据不想让用户填写,例如 auth_assignment、createdAt。所以我现在不知道如何使用为用户填充它的函数。我知道例如在 SignupForm 中我可以使用方法 save() 并且我可以使用函数 generate auth_key 例如。在模型中我经常使用这个函数:

public function saveProfile() {

        $model = $this->_user;
        $model->Name=$this->Name;
        $model->Surname=$this->Surname;
        $model->Login=$this->Login;
        $model->Rel_Sex= $this->Sex;
        $model->setAttributes($this->getAttributes());
        $model->BirthDate = $this->getDbFormatedDate();
        $model->Rel_Country = $this->Country;
        $model->Rel_Language = $this->Language;
        $model->Email = $this->Email;
        $model->Rel_UserCategory= $this->Category;
        $model->setPassword($this->Password);

       if ($this->validate() && $model->validate()) {
            $model->save();
            return $model;
        }
        return false;
    }

但我不知道如何覆盖 ActiveRecord 中的方法 save()。所以我让这个类扩展 ActiveRecord:

<?php

namespace backend\modules\users\models;

use Yii;
use yii\behaviors\TimestampBehavior;


class Uruser extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'uruser';
    }



    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Name', 'Surname', 'BirthDate', 'Login', 'Email', 'PasswordHash', 'created_at', 'Rel_Sex', 'auth_key', 'status', 'auth_assignment'], 'required'],
            [['BirthDate'], 'safe'],
            [['RulesAccept', 'created_at', 'updated_at', 'Rel_Sex', 'Rel_Country', 'Rel_Language', 'Rel_UserCategory', 'Rel_AccountType', 'Rel_RoyalUserData', 'Rel_EmailPermission', 'Rel_CommercialPermission', 'IsDeleted', 'status'], 'integer'],
            [['Name', 'Surname', 'Login', 'Email', 'PasswordResetToken', 'auth_key', 'auth_assignment'], 'string', 'max' => 45],
            [['PasswordHash'], 'string', 'max' => 90]
        ];
    }

我只填写电子邮件、生日、登录名、姓名。但我想使用一些函数来填充我的保存属性。比如生成AuthKey。

 public function setPassword($password)
    {
       return $this->PasswordHash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
       return $this->auth_key = Yii::$app->security->generateRandomString();
    }

我如何在保存时做到这一点?

当我使用之前保存它不起作用:

public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if($this->isNewRecord) {
                $this->generateAuthKey();
                $this->setPassword($this->PasswordHash);
                $this->status=1;
                $this->created_at=date('Y-m-d');
            }
            return true;
        } else {
            return false;
        }
    }

我 var_dum 在控制器中:

 public function actionCreate()
    {
        $model = new Uruser();

        var_dump($model->load(Yii::$app->request->post()), $model->save(),$model->getErrors());
        exit();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->Id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

我有这个:

bool(true) bool(false) array(3) { ["created_at"]=> array(1) { [0]=> string(27) "创建时间不能为空。" } [“auth_key”]=> 数组(1){ [0]=> string(25) "授权密钥不能为空。" } [“状态”]=> 数组(1){ [0]=> string(23) "状态不能为空。" } }

当我使用 beforeSave 现在更新密码时,它不会散列我的密码并看到我写的这个 waht。我在我的模型中尝试了这个,但它不起作用:

public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if($this->isNewRecord) {
                $this->created_at = date('Y-m-d H:i:s');
                $this->status = self::DEFAULT_STATUS;
                $this->generateAuthKey();
                $this->setPassword($this->PasswordHash);
                $this->RulesAccept=1;
            }
            return true;
        } else {
            $this->setPassword($this->PasswordHash);
            $this->updated_at = date('Y-m-d H:i:s');
            return true;
        }
    }

编辑后

 public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if($this->isNewRecord) {
                $this->created_at = date('Y-m-d H:i:s');
                $this->status = self::DEFAULT_STATUS;
                $this->generateAuthKey();
                $this->setPassword($this->PasswordHash);
                $this->RulesAccept=1;
                return true;
            }
            else {
            $this->setPassword($this->PasswordHash);
            $this->updated_at = date('Y-m-d H:i:s');
            return true;
        }
        } 
    }

这对我有用

【问题讨论】:

    标签: activerecord save yii2 overwrite


    【解决方案1】:

    您可以在模型中使用 beforeSave 方法。在插入或更新记录开始时调用此方法。如果您只想在插入新记录时保存新属性,则应使用 isNewRecord 属性。

    class Uruser extends \yii\db\ActiveRecord
    {
        public function rules()
        {
            return [
                [['Name', 'Surname', 'BirthDate', 'Login', 'Email', 'PasswordHash', 'Rel_Sex', 'auth_assignment'], 'required'],
                [['BirthDate'], 'safe'],
                [['RulesAccept', 'created_at', 'updated_at', 'Rel_Sex', 'Rel_Country', 'Rel_Language', 'Rel_UserCategory', 'Rel_AccountType', 'Rel_RoyalUserData', 'Rel_EmailPermission', 'Rel_CommercialPermission', 'IsDeleted', 'status'], 'integer'],
                [['Name', 'Surname', 'Login', 'Email', 'PasswordResetToken', 'auth_key', 'auth_assignment'], 'string', 'max' => 45],
                [['PasswordHash'], 'string', 'max' => 90]
            ];
        }
        ....
        public function beforeSave($insert)
        {
            if (parent::beforeSave($insert)) {
                if($this->isNewRecord) {
                    $this->created = date('Y-m-d H:i:s');
                    $this->status = self::DEFAULT_STATUS;
                    $this->generateAuthKey();
                    $this->setPassword($this->password);
                }
                return true;
            } else {
                return false;
            }
        }
        ....
    }
    

    更多信息here

    【讨论】:

    • 感谢您的回答,但它不起作用我不知道为什么我更新我的第一篇文章如果你有时间看看这个
    • 对不起。我没有注意到所需的规则。您遇到此错误是因为 created_at、auth_key 和 status 字段在规则方法中设置为必填字段。如果您在 rules 方法的所需部分中删除这些字段(created_at、auth_key、status)并在 beforeSave 方法中设置这些字段,它将起作用。我已经更新了我的答案。
    • 但是我还有一个问题要如何处理这个密码哈希它是用户给出的哈希密码,当我点击更新时它显示我哈希密码很多点甚至不知道它应该是什么样子,我能解决这个问题怎么办
    • 看看这个答案link。它应该有帮助。您在密码字段中设置了一个空值。当您更新用户配置文件中的字段时,您应该检查密码属性。如果它不为空,则创建密码哈希。
    • 好的,但是当我更新密码时没有密码,并且在数据库中保存了我写的内容而不是散列
    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多