Yii2如何实现乐观锁。 我正在尝试遵循此official doc.
这是我的程序。
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
],
];
}
}
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的公共功能behaviors()
在步骤1中重写此方法以返回此列的名称。 如何重写此方法。 我所缺少的。
答案 0 :(得分:1)
覆盖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';
}
}