ZF2 保存到多个表,(1)如果数据库出错回滚更改(2)显示数据库错误

ZF2 saving to multiple tables, (1) roll back changes if database error (2) display db errors

在 ZF2 中,我有一个将数据保存到 3 tables 中的映射器。 Table 1 只有 ids,tables 2 和 3 有 ids 和更多数据。 table依次填入:先是table1,然后是table2,然后是table3。

假设有一些东西阻止保存到第 3 个 table(例如唯一约束失败)。因为table是依次填的,所以table的1和2都填了,而3号没有。所以我在 tables 1 和 2 中留下了未使用的数据。

如果出现数据库错误,如何删除在 tables 1 和 2 中创建的值,并在第 3 个 table 中显示错误消息?

找到 SO 答案。

不过,这个答案没有具体说明如何实现对多个表的插入。关键是将所有插入内容放在 beginTransaction()commit() 方法之间,如下所示:

try {
    $this->getAdapter()->getDriver()->getConnection()->beginTransaction();

    // your inserts go here

    $this->getAdapter()->getDriver()->getConnection()->commit();
} catch (\Exception $e) {
    $this->getAdapter()->getDriver()->getConnection()->rollback();
    throw $e;
}

然后 rollback() 进入 catch 块。