如何使用php/yii在操作期间锁定表
我的桌子:如何使用php/yii在操作期间锁定表,php,mysql,yii,Php,Mysql,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,
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`)
)
我有以下问题:
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.)
}
此源代码来自以下帖子:在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();
使用“锁表”和“事务”之间有什么区别?事务使一组查询成为原子查询。阅读更多关于如何为事务设置isolationLevel的内容添加一些说明