How to implement mysql write lock in Yii2

I want to implement a write lock function in a Yii2 application.

If one user opens a link / update record (example http://localhost/myproject/backend/web/user/update/1 ), another user will not be able to access this link, and the user will receive an ALERT message that says: " This post has already been opened by another user. " Thus, the post / page should be blocked for another user. (Similar to MS Excel lock)

As soon as the first user finishes and leaves this record / page, he must be unlocked, and another user can read / update this data.

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

Any help would be appreciated.

+5
source share
2 answers

He called optimistic blocking and is described in official documents. The following is an example 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 } } 
+5
source

You can add the locked_by_user column to your table, and when someone requests an update action, you check the locked_by_user column if it is installed or not. If not, set it to user_id, which first requests the update action. You also need to worry about locked locks. And consider cases where the user can simply close the browser window, and then the record will be locked until he takes any action, such as saving the record or canceling editing.

+2
source

All Articles