找到许多作品,但删除许多没有



我有一个简单的注释表和一个带有隐式多对多关系的标签表。

model Tag {
id    Int    @id @default(autoincrement())
tag   String @unique
notes Note[]
}
model Note {
id    Int    @id @default(autoincrement())
note  String @unique
tags  Tags[]
...
}

当我删除一个笔记时,我想删除仅在该笔记中的标签。我这样写:

await prisma.tag.deleteMany({
where: {
notes: { none: { tags: { some: { tag: { in: tags } } } } }, // tags: string[] coming from deleted note
},
});

但是它给了我错误:

ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Server(ServerError { code: 1093, message: "You can't specify target table 'Tags' for update in FROM clause", state: "HY000" })) })

但是当我将它改为findMany时,它可以毫无问题地找到它们。有什么问题吗?

目前,我正在运行另一个deleteMany从findMany的数据。我读过,在纯SQL中,你可以包装它在另一个SELECT,但有什么我可以做在棱镜?

我找了很多才找到这个

你的问题来自mysql,我尝试用postgresql,我无法复制它。

但碰巧,有一个解决办法。

你的新prisma查询看起来像:

await prisma.tag.deleteMany({
where: {
// Search tag with no notes
notes: { none: {} },
// and in your list
tag: { in: tags }
},
});

编辑实际上,如果你不想要任何没有链接到注释的标签,你可以只做

await prisma.tag.deleteMany({
where: {
notes: { none: {} },
},
});

,因为它会搜索所有没有链接到注释的标签。唯一的问题是,它将检查Tag表中的所有标签,因此它不会真正有效

再解释一下notes: { none: {} }

使用模拟表

Relationship Note / Tag表:

╔═════════╦════════╗
║ node_id ║ tag_id ║
╠═════════╬════════╣
║ Note1   ║ Tag1   ║
║ Note1   ║ Tag2   ║
║ Note2   ║ Tag2   ║
║ Note3   ║ Tag3   ║
║ Note4   ║        ║
║ Note5   ║        ║
║         ║ Tag4   ║
║         ║ Tag5   ║
║         ║ Tag6   ║
║         ║ Tag7   ║
╚═════════╩════════╝

Notetable

╔═══════╦══════╗
║  id   ║ note ║
╠═══════╬══════╣
║ Note1 ║ a    ║
║ Note2 ║ b    ║
║ Note3 ║ c    ║
║ Note4 ║ d    ║
║ Note5 ║ e    ║
╚═══════╩══════╝

当您添加过滤器notes: { none: {} }时,您要求Prisma查找每个没有注释的标签,因此在Relationship Note / Tag表中没有关系

所以用这个过滤器找到许多:

const tags = await prisma.tag.findMany({
where: {
notes: { none: {} },
},
});

tags将包含idTag4,Tag5,Tag6Tag7的标签,因为它们与任何注释

无关。第二例

当你做notes: { none: { note: 'a' } }时,你要求Prisma找到任何没有notevalue =a注释的标签

所以用这个过滤器找到许多:

const tags = await prisma.tag.findMany({
where: {
notes: { none: { note: 'a' } },
},
});

tags将包含除Tag1Tag2外与Note1相关且notevalue =a的所有标签

结束编辑

供参考在这里,你没有做你想做的事情

notes: { none: { tags: { some: { tag: tags } } } }

你要求搜索tags,在注释标签中没有tags

如果你有这些关系

╔═════════╦════════╗
║ node_id ║ tag_id ║
╠═════════╬════════╣
║ Note1   ║ Tag1   ║
║ Note1   ║ Tag2   ║
║ Note2   ║ Tag3   ║
║ Note3   ║ Tag3   ║
╚═════════╩════════╝

然后删除Note3,然后用这个查询搜索Tag3,链接到Note2的Tag3有一些Tag3,所以没有删除,但是Tag2没有一些Tag3的注释,所以被删除,Tag1也一样

最新更新