'Relate existing User and Post in Prisma to create a favorites feature

I want a simple favorite feature. For that I need to connect an existing user with an existing post. I cannot really find an explanation in the Prisma docs, they only show how to make relations when creating a new post.

Here is my schema:

model User {
  uid String @id @default(uuid())
  username String? @db.VarChar(24) @unique  
  favorites FavoritesOnUsers[]

model Post {
  id             Int     @id @default(autoincrement())
  title           String  @db.VarChar(255)
  favoritedBy FavoritesOnUsers[]
}

model FavoritesOnUsers {
  user       User     @relation(fields: [userId], references: [uid])
  userId     String  
  post       Post @relation(fields: [postId], references: [id])
  postId     Int

  @@id([userId, postId])
}

So when the user likes a post and adds it to his favorites, how would such a query look like to combine the userId with the postId in the FavoritesOnUsers table?



Solution 1:[1]

Creating a record in the junction table should relate both entities:

await prisma.favouritesOnUsers.create({
  data: { userId, postId },
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ironolife