hi, I need some help my database is like this ```U...
# orm-help
t
hi, I need some help my database is like this
Copy code
User <-> 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
Copy code
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 out
1
m
@Tri Nguyen I think I understand what you're trying to do - have you figured it out? Consider that you write your models something like this
Copy code
model 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'.
t
yeah I think I figured that one out. What I ended up doing ii:
Copy code
prisma.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