从活动记录创建和更新用户

create and update user from active record

我在后端对 table 用户 class 进行了 CRUD 扩展 ActiveRecord。但是在我的 table 中,我有很多数据不想让用户填写,例如 auth_assignment,createdAt。所以我现在不知道如何使用为用户填充它的功能。我知道例如在 SignupForm 中我可以使用方法 save() 并且在那里我可以使用函数生成 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()。所以我有这个 class extend 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) "Created At cannot be blank." } ["auth_key"]=> array(1) { [0]=> string(25) "Auth Key cannot be blank." } ["status"]=> array(1) { [0]=> string(23) "Status cannot be blank." } }

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

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;
        }
        } 
    }

这对我有用

您可以在模型中使用 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