如何在操作期间使用php/yii锁定表


How to lock a table during an operation use php/yii

我的表:

CREATE TABLE IF NOT EXISTS `detail_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `id_product` int(11) NOT NULL,
  `id_store` int(11) NOT NULL,
  `input_quality` int(11) NOT NULL,
  `output_quality` int(11) NOT NULL,
  `quality_in_store` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

我的问题如下:

我得到的记录有max_id,然后在插入新记录之前,有插入了另一个进程插入新记录。

我想:我会在"我选择一个记录有max_id"到"我完成插入新的下一个记录"期间锁定表(不要用这个表运行任何任务)。并用这种方法。请帮帮我!如何通过php代码或Yii来做到这一点。

您可以使用事务:

$transaction = Yii::app()->db->beginTransaction();
try {
    foreach ($items as $item) {
        $item->attr = value;
        $item->save();
    }
    $transaction->commit();
    // actions to do on success (redirect, alert, etc.)
} catch (Exception $e) {
    $transaction->rollBack();
    // other actions to perform on fail (redirect, alert, etc.)
} 

这段源代码来自这篇文章:在yii 中循环使用事务

在Yii2中,您可以锁定/解锁像这样的表

$db = Yii::$app->getDb();
$db ->createCommand('LOCK TABLES `YOUR_TABLE` WRITE')->execute();
// access YOUR_TABLE here 
// something like YOUR_TABLE_MODEL::find()->where(["something" => "blah"])->one()
$db ->createCommand('UNLOCK TABLES')->execute();

我不确定你想要实现什么,但我相信如果你只使用事务-http://www.yiiframework.com/doc-2.0/yii-db-transaction.html.否则,您可以始终调用LOCK TABLE查询-http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html.

$connection = Yii::app()->db;
$lock = $connection-> createCommand('LOCK TABLES `detail_transactions` WRITE');
// do your magic
$unlock = $connection-> createCommand('UNLOCK TABLES');