如何在 Prisma 中创建或更新多对多关系?
How to create or update many-to-many relation in Prisma?
我有以下模型,以及它们之间的多对多关系:
model User {
id String @id @default(cuid())
name String?
email String? @unique
followings Artist[]
}
model Artist {
id String @id @default(cuid())
name String @unique
spotifyId String @unique
followers User[]
}
当用户登录我的应用程序时,我会检索他们当前关注的艺术家,并且需要更新我的数据库。
我已经设法从数据库中 select 艺术家数据(用于更新用户 <-> 艺术家关系),示例数据:
const followings = [
{
id: '...',
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A'
},
{
id: '...',
name: 'Dua Lipa',
spotifyId: '6M2wZ9GZgrQXHCFfjv46we'
},
]
现在,这是我的用户对象:
const user = {
id: 'someId',
name: 'someName',
email: 'someEmail'
}
我试图通过此查询插入或更新用户 <-> 艺术家关系,但我收到 Bad Request
错误:
await prisma.user.upsert({
where: {
email: user.email
},
create: {
name: user.name,
email: user.email,
followings: {
connectOrCreate: followings
}
},
update: {
followings: {
connectOrCreate: followings
}
}
})
请告知我需要做什么。提前致谢。
P.S。我从 post 那里得到了查询的想法,但它对我不起作用,所以请不要标记重复。
connectOrCreate
应该指定带有 id 的 where
键(这样 Prisma 可以找到这个实体)和带有所有必需模型字段的 create
键(这样 Prisma 可以创建它,如果它还没有的话) present),但你只是传递了一系列模型。将您的代码更改为这个代码:
await prisma.user.upsert({
where: {
email: 'user.email',
},
create: {
name: 'user.name',
email: 'user.email',
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
update: {
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
});
我有以下模型,以及它们之间的多对多关系:
model User {
id String @id @default(cuid())
name String?
email String? @unique
followings Artist[]
}
model Artist {
id String @id @default(cuid())
name String @unique
spotifyId String @unique
followers User[]
}
当用户登录我的应用程序时,我会检索他们当前关注的艺术家,并且需要更新我的数据库。
我已经设法从数据库中 select 艺术家数据(用于更新用户 <-> 艺术家关系),示例数据:
const followings = [
{
id: '...',
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A'
},
{
id: '...',
name: 'Dua Lipa',
spotifyId: '6M2wZ9GZgrQXHCFfjv46we'
},
]
现在,这是我的用户对象:
const user = {
id: 'someId',
name: 'someName',
email: 'someEmail'
}
我试图通过此查询插入或更新用户 <-> 艺术家关系,但我收到 Bad Request
错误:
await prisma.user.upsert({
where: {
email: user.email
},
create: {
name: user.name,
email: user.email,
followings: {
connectOrCreate: followings
}
},
update: {
followings: {
connectOrCreate: followings
}
}
})
请告知我需要做什么。提前致谢。
P.S。我从
connectOrCreate
应该指定带有 id 的 where
键(这样 Prisma 可以找到这个实体)和带有所有必需模型字段的 create
键(这样 Prisma 可以创建它,如果它还没有的话) present),但你只是传递了一系列模型。将您的代码更改为这个代码:
await prisma.user.upsert({
where: {
email: 'user.email',
},
create: {
name: 'user.name',
email: 'user.email',
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
update: {
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
});