gpt4 book ai didi

Yii2:如何在事务中禁用/启用自动提交模式?

转载 作者:行者123 更新时间:2023-12-02 17:26:30 24 4
gpt4 key购买 nike

在 Yii 1.1 中存在类 CDbConnection 属性 autoCommit .在 Yii2 中是类 Connection没有这样的属性(property)。我应该如何在事务中禁用和启用自动提交模式?或者我应该简单地使用以下方法:

$db->query('SET autocommit=0;');
$transaction = $db->beginTransaction();
try {
$model->save();
...
$transaction->commit();
} catch(Exception $e) {
$transaction->rollback();
}
$db->query('SET autocommit=1;');

最佳答案

因为 \yii\db\Connection::beginTransaction() 调用了 \yii\db\Transaction::begin(),所以不需要这个依次调用 PDO::beginTransaction()其中:

Turns off autocommit mode.

另外PDO::commit() :

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

也适用于 PDO::rollback() :

If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.

但是,您可以通过访问pdo 对象直接设置PDO 值\yii\db\Connection::$pdo并使用 PDO::setAttribute() :

$db->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);

您还可以使用 \yii\db\Connection::$attributesYii::$app->db 对象的初始化期间设置它们。在你的配置文件中:

'components' => [
'db' => [
'class' => '\yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'attributes' => [
PDO::ATTR_AUTOCOMMIT => false
]
],
],

关于Yii2:如何在事务中禁用/启用自动提交模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com