我的桌子:
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完成此操作。
发布于 2014-10-31 01:49:32
您可以使用事务:
$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.)
}
此源代码来自于以下文章:using transaction in a loop in yii
发布于 2014-10-31 01:49:02
我不太确定你想要实现什么,但我确信如果你只使用事务- http://www.yiiframework.com/doc-2.0/yii-db-transaction.html,它就会解决。否则,您可以始终调用锁表查询- 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');
发布于 2017-12-24 09:28:57
在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();
https://stackoverflow.com/questions/26671507
复制