Sequelize,插入后立即读取插入行的id而不提交事务

Sequelize, reading the id of inserted row right after inserting it without commiting the transaction

对我来说,完美的解决方案是插入一个带有一些子关联的父模型,并级联创建子关联。但是,当我开始使用 Sequelize 并且我确实设法让它工作时,我需要插入数据并手动设置关联以使其工作。

基本上,插入父行后,我需要能够获取自动递增的 ID(由 mysql 管理的序列,而不是 sequelize),以便将该 ID 作为外键分配给子实体. 理想情况下,我希望在事务中以原子方式执行所有内容,这样如果出现问题,我们将回滚所有内容。 也就是说,除非我在插入后手动提交事务,否则我无法获取父实体的 ID。有没有办法在事务提交之前读取值,一些脏读?

这是目前的代码:

const ipiInterestedParty = {
            ip_base_nr: '118',
        };
    const transaction = await session.transaction();
    const instance = await IpiInterestedParty.create(ipiInterestedParty, {transaction});
    await transaction.commit();
        const createdWithId = await IpiInterestedParty.findOne({
            where: {ip_base_nr: '118'}
        });

这是我唯一能够得到parent id的方法,但是,由于事务已经提交,万一之后出现任何错误,事务已经提交且无法撤消, 使系统不一致。

有什么帮助吗?

如果您在模型的 PK autoIncrement: true 中指定,通常在执行模型的 create 方法后,您会得到 instance 和主键值。 这样你就已经有了一个 parent 记录的 id 来创建子记录。不要忘记将事务对象传递给在事务中进行 CRUD 的所有方法。