我在Yii2中使用乐观锁定编写待办事项应用程序。
我现在需要写更新动作。我试着写模型,控制器和视图来达到这个目的。
我使用此文档链接:www.example.com我的型号:https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#optimistic-locks My model:
<?php
namespace app\models;
use yii\behaviors\OptimisticLockBehavior;
use yii\db\ActiveRecord;
class RecordModel extends ActiveRecord
{
public static function tableName()
{
return 'records';
}
public function behaviors()
{
return [
OptimisticLockBehavior::class,
];
}
public function optimisticLock()
{
return 'version';
}
}
我的控制器:
<?php
namespace app\controllers;
use Yii;
use app\models\RecordModel;
use yii\db\StaleObjectException;
class RecordController extends AppController
{
public function actionUpdate($id=1)
{
$model = RecordModel::find()->where(['id' => $id])->one();
//debug($model);die();
try {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', 'Success');
return $this->refresh();
} else {
return $this->render('update', [
'model' => $model,
]);
}
} catch (StaleObjectException $e) {
Yii::$app->session->setFlash('error', 'Error');
}
}
我的update.php文件
<h1>index</h1>
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php if( Yii::$app->session->hasFlash('success') ): ?>
<div
class="alert alert-success alert-dismissible"
role="alert"> <button type="button" class="close"
data-dismiss="alert"
aria-label="Close"><span
aria-hidden="true">×</span></button>
<?php echo Yii::$app->session->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php if( Yii::$app->session->hasFlash ('error') ): ?>
<div class="alert alert-danger alert-dismissible"
role="alert"> <button type="button"
class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span></button>
<?php echo Yii::$app->session->getFlash('error'); ?>
</div>
<?php endif; ?>
<? $form = ActiveForm::begin();?>
<?= $form->field($model, 'text')->label('Text');?>
<? echo Html::activeHiddenInput($model, 'version');?>
<?= Html::submitButton('Send', ['class' => 'btn btn-success']);?>
<? ActiveForm::end();?>
但是我的代码好像没有做我想做的事情。请帮帮我!
1条答案
按热度按时间13z8s7eq1#