简体   繁体   English

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

[英]How to implement mysql record locking in Yii2

I want to implement record locking functionality in my Yii2 application. 我想在我的Yii2应用程序中实现记录锁定功能。

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 ". 如果一个用户打开更新链接/记录(例如http://localhost/myproject/backend/web/user/update/1 ),则另一个用户无法访问此链接,用户将收到一条ALERT消息“ 此记录已打开由另一个用户 “。 So the record/page should lock for another user. 所以记录/页面应锁定另一个用户。 (Same like MS Excel locking) (与MS Excel锁定相同)

Once first user finishes and leaves from that record/page then it should unlock and another user can read/update that data. 一旦第一个用户完成并离开该记录/页面,它就应该解锁,另一个用户可以读取/更新该数据。

So how can I use mysql database locking mechanism here in Yii2 active records or is there any other way to implement this. 那么如何在Yii2活动记录中使用mysql数据库锁定机制,还是有其他方法来实现它。

Any help would be appreciated. 任何帮助,将不胜感激。

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
    }
}

You can add column locked_by_user to your table and when someone is requested update action you check locked_by_user column if it is set or not. 您可以向表中添加列locked_by_user ,当有人请求更新操作时,如果已设置,则检查locked_by_user列。 If not, set it to the user_id who is request update action first. 如果没有,请将其设置为首先是请求更新操作的user_id。 Also you need to be concerned about reseting locks . 您还需要关注重置 And consider cases when user just can close the browser window and then record will be locked until he makes any action like save record or cancel editing . 并考虑用户只是关闭浏览器窗口然后记录将被锁定直到他做出保存记录取消编辑等任何操作的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM