php - Yii2如何实现乐观锁
问题描述
Yii2 如何实现乐观锁。我正在尝试关注这个官方文档。
这是我的程序。
2.模型.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
],
];
}
}
我的控制器.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()
在步骤 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';
}
}
推荐阅读
- node.js - 软件包在 NMP 安装时被删除
- javascript - 如何使用 Vue.js 下载图像而不显示它们?
- python - 序列化程序调用显示 TypeError:“ListSerializer”类型的对象不是 JSON 可序列化的?
- vuejs2 - 实现:无法在 Dropdown._makeDropdownFocusable 处设置属性“tabIndex”为空
- swift - 如何获取 MacOS Xcode 项目中使用的 sparkle 框架的当前版本
- android - Android 7.0:自定义通知声音不再起作用
- npm - Gitlab CI:在存储库中创建 dist 文件夹?
- ios - 如何在 Swift 中为按钮的属性不重复代码?
- .net - “Stripe.Infrastructure.StripeTypeRegistry”的类型初始化器抛出异常?
- arrays - Angular 仅显示符合 *ngIf 特定条件的数组元素?