如何在Yii2中实现mysql记录锁定

如何在Yii2中实现mysql记录锁定

本文介绍了如何在Yii2中实现mysql记录锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Yii2应用程序中实现记录锁定功能.

I want to implement record locking functionality in my Yii2 application.

如果一个用户打开更新链接/记录(例如http://localhost/myproject/backend/web/user/update/1),则另一用户将无法访问此链接,并且该用户将收到一条ALERT消息,内容为"该记录已被另一用户打开 ".因此,记录/页面应为另一个用户锁定. (类似于MS Excel锁定)

If one user opens update link/record (Ex.http://localhost/myproject/backend/web/user/update/1) then another user cannot able to access thislink and user will get an ALERT message saying "This record already opened by another user". So the record/page should lock for another user. (Same like MS Excel locking)

一旦第一个用户完成该记录/页面上的操作并离开该记录/页面,然后它将解锁,另一个用户可以读取/更新该数据.

Once first user finishes and leaves from that record/page then it should unlock and another user can read/update that data.

那么我该如何在Yii2活动记录中使用mysql数据库锁定机制,或者是否有其他方法可以实现此目的.

So how can I use mysql database locking mechanism here in Yii2 active records or is there any other way to implement this.

任何帮助将不胜感激.

推荐答案

它称为乐观锁定,在官方文档.这是一个实现示例:

It's called Optimistic Locking and described in official docs. Here is an example of implementation:

// ------ view code -------

use yii\helpers\Html;

// ...other input fields
echo Html::activeHiddenInput($model, 'version');


// ------ controller code -------

use yii\db\StaleObjectException;

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    try {
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    } catch (StaleObjectException $e) {
        // logic to resolve the conflict
    }
}

这篇关于如何在Yii2中实现mysql记录锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:59