Home > Net >  How to update an entity using it's foreign key in Prisma?
How to update an entity using it's foreign key in Prisma?

Time:08-14

I have a simple API where authenticated users are allowed to perform CRUD operations on videos. The Video model holds a foreign key called creatorId, which references the User model that created it. I'm trying to update the video by passing the creatorId into the where clause of the Prisma function, however I am getting the following error:

Unknown arg `creatorId` in where.creatorId for type VideoWhereUniqueInput. Available args:

type VideoWhereUniqueInput {
  id?: Int
}

Here is my attempt using Express JS.

export const updateVideo = async (req, res, next) => {

    const userId = parseInt(req.user.id)
    const videoId = parseInt(req.params.id)

    try {

        // check if video exists or not
        const videoToUpdate = await prisma.video.findUnique({
            where: {
                id: videoId
            }
        })

        // if no video was found throw an error
        if (!videoToUpdate)
            return next(createError(404, `Video with ID ${req.params.id} does not exist`))

        // update the video
        const updatedVideo = await prisma.video.update({

            // find video that was created by the user
            where: {
                creatorId: userId
            },

            // data to change
            data: {
                ...req.body,
            }
        })

        res.status(200).json(updatedVideo)
    } 

    catch (error) {
        console.log(error)
        next(error)
    }
}

And here are my Prisma models:

model User {
  id Int @id @default(autoincrement())
  email String @unique 
  name String
  password String
  img String?
  subscriberCount Int? @default(0)
  videos Video[]
  comments Comment[]
  followedBy Follows[] @relation("following")
  following Follows[] @relation("follower")
  likedVideos Likes[]
}

model Video {
  id Int @id @default(autoincrement())
  creator User @relation(fields: [creatorId], references: [id])
  creatorId Int 
  title String 
  description String 
  videoUrl String?
  views Int? @default(0)
  tag String? @default("Uncategorized")
  likedBy Likes[]
  comments Comment[]
}

How can I fix this such that Prisma can do the update query based on the Foreign key? I'm aware there are ways around this issue that don't involve using the Foreign key like this, but I'm just curious as to why my naive solution doesn't work. For example, why would a similar approach work with a primary key but not a foreign one?

CodePudding user response:

Add the @unique attribute to the creatorId field. Prisma only allows unique fields to be specified in where clauses.

  • Related