Transactions 尽管下一个事务步骤失败,但将实体保存到数据库的类型化事务
我想创建一个事务来保存一个新表行以及该行的多对多帮助器表条目。我使用相同的事务管理器保存这两个部分,但当第二部分失败时,第一部分不会恢复。为什么会这样Transactions 尽管下一个事务步骤失败,但将实体保存到数据库的类型化事务,transactions,typeorm,Transactions,Typeorm,我想创建一个事务来保存一个新表行以及该行的多对多帮助器表条目。我使用相同的事务管理器保存这两个部分,但当第二部分失败时,第一部分不会恢复。为什么会这样 await getManager().transaction(async transactionalEntityManager => { newFeed = await transactionalEntityManager .createQueryBuilder() .insert()
await getManager().transaction(async transactionalEntityManager => {
newFeed = await transactionalEntityManager
.createQueryBuilder()
.insert()
.into(Feed)
.values({ ...feed })
.execute();
console.log('======================================\n', newFeed);
feed.sources.forEach(async source => {
console.log('==in forEach===\n', source.id, newFeed.identifiers[0].id);
await transactionalEntityManager
.createQueryBuilder()
.insert()
.into('feed_source')
.values({
sourceId: source.id,
feedId: newFeed.identifiers[0].id,
fontColor: feed.fontColor ? feed.fontColor : null,
postColor: feed.postColor ? feed.postColor : null
})
.execute();
});
});
这与语法有关吗?我以前没有使用过insert查询生成器语法。.execute()是否以某种方式忽略了事务?这样做的正确方法是什么?好的,所以我解决了它。这是因为forEach的行为似乎是异步的,因此代码会在完成循环之前跳到事务的末尾。在寻找解决方案时,我改变了我使用的方法和一些功能,因此代码的结果非常不同,但主要的是我使用了Promise.all()并将返回promises的.map()的结果传递给它
await getManager().transaction(async transactionalEntityManager => {
savedFeed = await transactionalEntityManager.save(newFeed);
if (feed.feedSources) {
newFeed.feedSources = [];
await Promise.all(
feed.feedSources.map(async feedSource => {
return new Promise(async (resolve, reject) => {
const referencedSource = await Source.findOne(feedSource.sourceId);
console.log('===referencedSource===\n', referencedSource);
if (!referencedSource)
throw new Error(
'Could not find referenced source with id ' + feedSource.id
);
const currentFeedSource = new FeedSource();
currentFeedSource.source = referencedSource;
currentFeedSource.feed = savedFeed;
feedSource.postColor
? (currentFeedSource.postColor = feedSource.postColor)
: '';
feedSource.fontColor
? (currentFeedSource.fontColor = feedSource.fontColor)
: '';
console.log('===currentFeedSource===\n', currentFeedSource);
await transactionalEntityManager.save(currentFeedSource);
resolve(true);
});
})
);
}