【问题标题】:get posts by tag Id using Prisma.js使用 Prisma.js 按标签 ID 获取帖子
【发布时间】:2021-09-11 04:51:05
【问题描述】:

如何通过过滤tagId获得帖子?

我测试了这段代码,但它不起作用: 我得到了所有没有过滤的帖子!

prisma.post.findMany({
      include:
      {
        Tags:
        {
          where: { TagId: tagId  },
          include:
          {
            Tag: true
          }
        }
      },
    })

schema.prisma:

model Post {
  id    Int        @id @default(autoincrement())
  title String
  tags  PostTags[]
}

model PostTags {
  id     Int   @id @default(autoincrement())
  post   Post? @relation(fields: [postId], references: [id])
  tag    Tag?  @relation(fields: [tagId], references: [id])
  postId Int?
  tagId  Int?
}

model Tag {
  id    Int        @id @default(autoincrement())
  name  String     @unique
  posts PostTags[]
}

我该如何解决这个问题?

【问题讨论】:

    标签: node.js orm prisma prisma2


    【解决方案1】:

    您需要在主查询中而不是在include 中过滤它。 include 仅用于获取关系然后在其中过滤,不会影响主查询。

    您的最终查询将如下所示:

    await prisma.post.findMany({ 
      where: { tags: { some: { tag: { id: 1 } } } } 
    })
    
    

    您可以阅读有关查询关系 here 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多