Tri Nguyen
07/15/2022, 2:42 AMUser <-> UserPost <-> Post
So user and post are many-to-many and I explicit state a table called userpost in between. How can I select user that is linked with post?
My initial try is
prisma.post.user.findMany({
where: {
links: {// I called the middle table link in schema
every: {
post: myPost,
}
}
}
})
but I don’t think that’s what I should do since it’s filtering. Can someone help me outMichael Jay
07/18/2022, 12:52 PMmodel User {
id String @id
userPosts UserPost[]
other User properties
}
model Post {
id String @id
userPosts UserPost[]
other Post properties
}
model UserPost {
user User @relation(fields: [userId], references: [id])
userId String
post Post @relation(fields: [postId], reerences: [id])
postId String
}
If you want to find all Users associated with a given Post (by post.id), then
prisma.UserPost.findMany({
where: { postId: post.id },
includes: { user: true }
})
This should make sense - if multiple users can be associated with the same post, then you want to find all of the UserPost records with the PostId - each of which is attached to a user through the UserId. The return value would be an array of UserPost objects, each of which has a 'user'
For instruction's sake, you could also:
prisma.Post.findUnique({
where: { id: post.id },
includes: {
userPosts: {
includes: { users: true }
}
}
})
Here, the return value would be a SINGLE Post record, with an array of 'userPosts', EACH of which had a 'user'.
Tri Nguyen
07/18/2022, 9:01 PMprisma.post.findMany({
where: {
userPost: {
some: {
userId: user.id
}
}
}
})
The way I understand this is: find the post where some of the post's users matches the user id, which in this case match exactly what I want