【问题标题】:Multiple filters with relation on Prisma 2与 Prisma 2 相关的多个过滤器
【发布时间】:2020-10-13 19:01:55
【问题描述】:

我想知道当一个过滤器是一个关系时,如何在 Prisma 2 中使用多个过滤器。我搜索了一篇具有特定 ID 和特定作者(安全原因)的帖子。

我阅读了documentation 并尝试申请:

const postExists = await prisma.post.findMany({
    where: {
        AND: [
            {
                id: {
                    equals: parseInt(args.id, 10), // args.id => 770 
                },
            },
            {
                author: {
                    id: {
                        equals: parseInt(userId, 10), // userId => 584
                    },
                },
            },
        ],
    },
})

在我的数据库中我有这个:

但如果我不是作者,我找到了我的帖子(例如,作者 ID 1)

const postExists = await prisma.post.findMany({
    where: {
        AND: [
            {
                id: {
                    equals: parseInt(args.id, 10), // args.id => 770 
                },
            },
            {
                author: {
                    id: {
                        equals: parseInt(userId, 10), // userId => 1
                    },
                },
            },
        ],
    },
})

在我的 schema.prisma 我有这个:

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

  @@index([fk_user_id], name: "fk_user_id")
}

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

【问题讨论】:

    标签: node.js apollo-server prisma


    【解决方案1】:

    关系字段

    您的第二个过滤器应该使用fk_user_id 而不是author

    authorposts 字段分别是 PostUser 中的虚拟字段。它们被称为关系字段。关系字段在 Prisma 级别定义模型之间的连接,它们不存在于实际的数据库表中。

    fk_user_id 代表创建 Post 的作者 (User)。

    此外,由于在您的情况下,您总是会得到一个 Post,因此请使用 findFirst() 而不是 findMany()。这样,您就不必处理Array


    使用多个过滤器

    这是修改后的代码:

    const postExists = await prisma.post.findFirst({
        where: {
            AND: [
                {
                    id: {
                        equals: parseInt(args.id, 10) 
                    }
                },
                {
                    fk_user_id: {
                        equals: parseInt(userId, 10)
                    }
                },
            ],
        },
    })
    

    请注意,我们删除了两个级别 author:id: 并仅插入了一个级别 fk_user_id:。我们还删除了不必要的逗号。

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      相关资源
      最近更新 更多