如何删除与自定义属性的整个多对多关系



我使用的实体与这里描述的实体类似。当我从post.postToCategories中删除值时,TypeORM不会删除带有记录的整行,而是将关系的一侧设置为null——分离问题。

如何删除整行?

虽然为时已晚,但我将把解决方案保留在这里,以供其他遇到相同问题的人使用,即删除包含自定义属性的多对多关系的连接

考虑到有两个实体UserPost具有它们的多对多连接实体,它们具有名为UserPost:的自定义属性

const user_post_connections: UserPosts[] = await this.userPostRepository.find(
{
where: {
user: user,
},
},
);
if (user_post_connections?.length) {
await this.userPostRepository.remove(user_post_connections);
}

注:此解决方案严格适用于本问题中提到的带有此设置参考的情况。

这应该可以通过orphanedRowAction选项解决。假设您有一个连接userpostPostConnections连接表,您可以将orphanedRowAction: 'delete'添加到每个ManyToOne关系中,如下所示:

@ManyToOne(
() => User,
(user) => user.postConnections,
{ orphanedRowAction: 'delete' },
)
user: User;
@ManyToOne(
() => Post,
(post) => post.postConnections,
{ orphanedRowAction: 'delete' },
)
post: Post;

最新更新