Multiple filters with relation on Prisma 2

Viewed 5280

I would like to know how can I use multiple filter with Prisma 2 when almsot one filter is an relation. I search one post with specific ID and specific author (security reason).

I read the documentation and I try to apply with this :

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
                    },
                },
            },
        ],
    },
})

In my database I have this :

enter image description here

But I found my post if I'm not the author (for example, author 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
                    },
                },
            },
        ],
    },
})

In my schema.prisma I have this :

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?
}
1 Answers

Relation Fields

Your second filter should be with fk_user_id instead of author.

The fields author and posts are virtual fields in Post and User respectively. They are called relation fields. The relation fields define connections between models at the Prisma level and they do not exist in the actual database tables.

It's the fk_user_id that represents the author (User) who created the Post.

Also, since in your case, you'll always get a single Post as a result, use findFirst() instead of findMany(). This way, you won't have to deal with an Array.


Using Multiple Filters

Here's is the rectified code:

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

Notice that we removed two levels author: and id: and inserted just one level fk_user_id:. We also removed unnecessary commas.

Related