-1

\yii\db\ActiveRecord私は自分のクラスで既存のものをオーバーライドしました。私がオーバーライドしたメソッドはbeforeSave(). 使用法に関するドキュメントを読みました。しかし、レコードが新しいレコードかどうかを確認すると、2回呼び出されていることがわかりました。

これは私のコードです:

class ActiveRecord extends \yii\db\ActiveRecord{
    public $count = 0;
    public function beforeSave($insert) {
        print($this->count++); //i try to investigate it deeper using this "count" property
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                print("123"); //this printed out
                if($this->hasAttribute('user_create')){
                    $this->user_create = \Yii::$app->user->identity->id;
                }
                if($this->hasAttribute('time_create')){
                    $this->time_create = new \yii\db\Expression('now()');
                }
            }
            else{
                print("456"); //and this is also
                if($this->hasAttribute('user_upd')){
                    $this->user_upd = \Yii::$app->user->identity->id;
                }
                if($this->hasAttribute('time_upd')){
                    $this->time_upd = new \yii\db\Expression('now()');
                }
            }
            return true;
        }else{
            return false;
        }
    }
}

新しいレコードを保存したときのコードの出力は次のとおりです

01231456
4

1 に答える 1

0

コントローラ側でミスを犯しました。これが私のコードです

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

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        if ($model->save()) {
            echo Json::encode(array('status' => 1));
        } else {
            echo Json::encode(array('status' => 0, 'message' => \kartik\widgets\ActiveForm::validate($model)));
        }
    } else {
        return $this->renderAjax('create', [
                    'model' => $model,
        ]);
    }
}

$model->save() を 2 回使用するべきではありません。

于 2015-09-14T08:13:47.593 に答える