1

我现在正在使用 prisma 进行项目。我设计了 m 对 n 关系表。下面是我的代码。模式棱镜

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")
}

这是我的棱镜代码。我想要做的是按曲目名称搜索并使用艺术家姓名获取所有曲目的信息。

+edit)我尝试过的是

// 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 获取每首曲目的艺术家姓名。有没有办法通过一个查询一次做到这一点?我很确定会有更好的方法来做到这一点。先感谢您。

4

1 回答 1

2

根据您的架构,include将不包含Artist关系。它必须包含在Artists_Tracks这样的关系中:

const result = await prisma.tracks.findMany({
    include: {
      Albums: {
        select: { cover: true },
      },
      Artists_Tracks: { include: { Artists: true } },
    },
})

通过这种方式,您可以获得Artist每个轨道的存在。

于 2020-12-08T12:51:51.953 回答