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

时间:2016-02-09 18:40:23

标签: activerecord save yii2 overwrite

我在类的用户表的后端做了CRUD扩展ActiveRecord。但在我的表中我有很多数据,我不想让用户填写例如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”] =&gt; array(1){[0] =&gt;   string(27)“Created At不能为空。” } [“auth_key”] =&gt; array(1){   [0] =&GT; string(25)“Auth Key不能为空。” } [“status”] =&gt; array(1){   [0] =&GT; string(23)“状态不能为空。” }}

当我使用之前保存时,我更新密码,然后它没有哈希我的密码和sawe这是我写的。我在我的模型中尝试这个但是它不起作用:

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

这项工作对我来说

1 个答案:

答案 0 :(得分: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