Yii2如何实现乐观锁

Yii2 how to implementation Optimistic Locks

Yii2如何实现乐观锁。 我正在尝试遵循此 official doc.

我以为我仔细按照步骤操作。 但仍然错误:

这是我的程序。

  1. 在数据库中创建一个列“version defualt velue = '0'

2.Model.php

use yii\behaviors\OptimisticLockBehavior;

class OptimisticTest extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return 'optimistictest';
    }


    public function rules()
        {
            return [
                [['version'], 'required'],
                [['created_by', 'updated_by','version'], 'integer'],
            ];
        }

  public function behaviors()
    {
        return [
            [
               'class' => TimestampBehavior::className(),
                'value' => new Expression('NOW()'),
            ],
            [
               'class' => BlameableBehavior::className(),
            ],
            [
                 'class' => OptimisticLockBehavior::className(), //'getLockAttribute' =>$this->version
           ],
        ];
    }

}
  1. myController.php

     public function actionUpdate($id)
    {
      $model = $this->findModel($id);
      $tempDocs = $model->docs;
      $modelRunning = $this->findModelRunning($model->running_id);
      $model->scenario = 'update';
     try {
        if ($model->load(Yii::$app->request->post()) &&
            $modelRunning->load(Yii::$app->request->post()) &&
            Model::validateMultiple([$model,$modelRunning]))
        {
          if($modelRunning->save())
            {
            $this->CreateDir($model->ref);
            $model->docs = $this->uploadMultipleFile($model,$tempDocs);
            $model->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'modelRunning' => $modelRunning,
            ]);
        }
    } catch (StaleObjectException $e) {
        // logic to resolve the conflict
          Yii::$app->session->setFlash('danger',Yii::t('app', 'Record can not be updated, there is a user associated with it'));
            return $this->redirect(['index']);
    }}
    

错误来自 Model.php 中的 public 函数 behaviors()

在步骤 1 中。将此方法重写为 return 此列的名称。 如何覆盖此方法。 我缺少什么。

覆盖 optimisticLock() 方法意味着,您必须在模型中实现该方法,以便可以使用它来代替默认实现。

您的模型应该如下所示

class OptimisticTest extends \yii\db\ActiveRecord
{
    //... your other methods in model

    public function optimisticLock()
    {
        //this method should return the name of version attribute
        return 'version';
    }
}