Doctrine DBAL Transactions

问题描述:

我真的不明白如何在DBAL中执行交易Doctrine DBAL Transactions

我有以下脚本正在根据行的id更新列。我放了一个不存在于表中的伪造ID(因此使得更新无法进行),但是尽管它是一个事务,但第一次更新仍被提交。如果其中一个失败,我希望所有的交易都会失败。

$conn -> beginTransaction(); 
    try{ 
     $try = $conn->prepare("update table set column = '123' where id = 0"); //column exists 
     $try->execute(); 
     $try = $conn->prepare("update table set column = '123' where id = 1"); //column exists 
     $try->execute(); 
     $try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists 
     $try->execute(); 

     $try = $conn->commit(); 
    } 
    catch(Exception $e) { 
     $try = $conn->rollback(); 
     throw $e; 
    } 

预期的结果,没有更新,因为行使用id = 120不存在 真实结果,所有行除了不存在的行更新。

我提前道歉,但面向对象的编程仍然是我的南极。

我知道这个问题已经很老了,所以如果有人遇到类似的问题未来,我会解释一些事情,因为这种行为不是错误。

$try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists 
$try->execute(); 

这里更新条件引用不存在的列,因此查询不会失败,它会更新0(零)行;在Doctrine中,受影响的行数由​​方法返回。

你可以抛出一个怀疑来触发回滚。

$try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists 
$affected = $try->execute(); 
if ($affected == 0) { 
    throw new Exception('Update failed'); 
} 

只有在引发Exception时,此代码才会回滚事务。

更新不成功时,它返回false,而不是异常。

您可以尝试无例外:

$try = $conn->commit(); 
if (!$try) { 
    $conn->rollback(); 
} 

,或者当结果是false抛出异常。

+2

它看起来像$ try = $ conn-> commit();不会把$试着变成一个布尔...没有什么真的似乎发生? – Mallow