如何在 prisma 中搜索 M 到 N 的关系?
How to search M to N relationship in prisma?
我现在正在用 prisma 做项目。
我设计了 m 到 n 的关系 table。下面是我的代码。
schema.prisma
model Artists {
id Int @id @default(autoincrement())
artistName String?
Albums Albums[]
Artists_Tracks Artists_Tracks[]
}
model Artists_Tracks {
id Int @id @default(autoincrement())
trackId Int?
artistId Int?
Artists Artists? @relation(fields: [artistId], references: [id])
Tracks Tracks? @relation(fields: [trackId], references: [id])
@@index([artistId], name: "Artists_Tracks_artistId_foreign_idx")
@@index([trackId], name: "Artists_Tracks_trackId_foreign_idx")
}
model Tracks {
id Int @id @default(autoincrement())
trackName String?
albumTrackNumber Int?
albumId Int?
Albums Albums? @relation(fields: [albumId], references: [id])
Artists_Tracks Artists_Tracks[]
@@index([albumId], name: "Tracks_albumId_foreign_idx")
}
这是我的棱镜代码。我想做的是按曲目名称搜索并获取所有曲目的信息和艺术家的名字。
+编辑)
我试过的是
// first try
optObj.include = {
Albums: {
select: { cover: true },
},
Artists_Tracks: {
Albums: true
},
};
// second try
optObj.include = {
Albums: {
select: { cover: true },
},
Artists_Tracks: true,
Artists: true,
};
const result = await prisma.tracks.findMany(optObj);
并使用 promise.all 获取每首曲目的艺术家姓名。有什么办法可以一次查询完成吗?我很确定会有更好的方法来做到这一点。提前谢谢你。
根据您的架构,include
将不包含 Artist
关系。它必须包含在 Artists_Tracks
关系中,如下所示:
const result = await prisma.tracks.findMany({
include: {
Albums: {
select: { cover: true },
},
Artists_Tracks: { include: { Artists: true } },
},
})
通过这种方式,您可以获得每首曲目的 Artist
。
我现在正在用 prisma 做项目。 我设计了 m 到 n 的关系 table。下面是我的代码。 schema.prisma
model Artists {
id Int @id @default(autoincrement())
artistName String?
Albums Albums[]
Artists_Tracks Artists_Tracks[]
}
model Artists_Tracks {
id Int @id @default(autoincrement())
trackId Int?
artistId Int?
Artists Artists? @relation(fields: [artistId], references: [id])
Tracks Tracks? @relation(fields: [trackId], references: [id])
@@index([artistId], name: "Artists_Tracks_artistId_foreign_idx")
@@index([trackId], name: "Artists_Tracks_trackId_foreign_idx")
}
model Tracks {
id Int @id @default(autoincrement())
trackName String?
albumTrackNumber Int?
albumId Int?
Albums Albums? @relation(fields: [albumId], references: [id])
Artists_Tracks Artists_Tracks[]
@@index([albumId], name: "Tracks_albumId_foreign_idx")
}
这是我的棱镜代码。我想做的是按曲目名称搜索并获取所有曲目的信息和艺术家的名字。
+编辑) 我试过的是
// first try
optObj.include = {
Albums: {
select: { cover: true },
},
Artists_Tracks: {
Albums: true
},
};
// second try
optObj.include = {
Albums: {
select: { cover: true },
},
Artists_Tracks: true,
Artists: true,
};
const result = await prisma.tracks.findMany(optObj);
并使用 promise.all 获取每首曲目的艺术家姓名。有什么办法可以一次查询完成吗?我很确定会有更好的方法来做到这一点。提前谢谢你。
根据您的架构,include
将不包含 Artist
关系。它必须包含在 Artists_Tracks
关系中,如下所示:
const result = await prisma.tracks.findMany({
include: {
Albums: {
select: { cover: true },
},
Artists_Tracks: { include: { Artists: true } },
},
})
通过这种方式,您可以获得每首曲目的 Artist
。