next.js Prisma Findmany多对多获取所有信息

cunj1qz1  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

Prisma FindMany Includeexample(https://www.prisma.io/docs/getting-started/quickstart)中,我们的数据模型为:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

字符串
而findMany函数为:

...

async function main() {
  const usersWithPosts = await prisma.user.findMany({
    include: {
      posts: true,
    },
  })
  console.dir(usersWithPosts, { depth: null })
}

...


结果是:

[
  { id: 1, email: '[email protected]', name: 'Alice', posts: [] },
  {
    id: 2,
    email: '[email protected]',
    name: 'Bob',
    posts: [
      {
        id: 1,
        title: 'Hello World',
        content: null,
        published: false,
        authorId: 2
      }
    ]
  }
]


因此,在postsJSON结果中,我们有id,title,content,published和authorId。
我的问题是:我可以有
作者名吗?**有没有办法得到它?我想要这样的结果:

[
  { id: 1, email: '[email protected]', name: 'Alice', posts: [] },
  {
    id: 2,
    email: '[email protected]',
    name: 'Bob',
    posts: [
      {
        id: 1,
        title: 'Hello World',
        content: null,
        published: false,
        authorId: 2,
        name: 'Bob', // I want the name here to show in the front-end directly
      }
    ]
  }
]


有没有办法做到这一点?谢谢。
我试着在包含和其他事情中包含,但都给出了服务器错误。

55ooxyrt

55ooxyrt1#

好吧,我解决了这个问题(只为像我这样被困在这个问题中的人报道):

const result = await prisma.openings.findMany({
         include: {
            creator: {
               include: {
                  user: true,
               }
            },
            labels: {
               include: {
                  openingLabel: true,
               }
            }
         },
      });

字符串
你可以像这样嵌套包含.

相关问题