I am trying to get all posts from followed users such that the posts have not been liked by the following user (aka me).
how can i create a schema and query such a thing?
I currently have this:
model User {
id String @id @default(autoincrement())
username String
followers Follows[] @relation("follower")
following Follows[] @relation("following")
likes Post[] @relation(references: [id])
}
model Follows {
follower User @relation("follower", fields: [followerId], references: [id])
followerId String
following User @relation("following", fields: [followingId], references: [id])
followingId String
@@id([followerId, followingId])
}
model Post {
id Int @id @default(autoincrement())
title String
likedBy User[] @relation(references: [id])
}
CodePudding user response:
There are a few problems in the schema:
- The relation in
Follows
table seemed reversed, (i.e.followerId
should be mapped to thefollowing
relation on theUser
model - I assume each post is made by a user, so I added the
author
field in thePost
model autoincrement()
usesInt
type, socuid()
is used instead inUser
model
Updated schema:
model User {
id String @id @default(cuid())
username String
followers Follows[] @relation("follower")
following Follows[] @relation("following")
posts Post[] @relation("author")
likes Post[] @relation(references: [id])
}
model Follows {
follower User @relation("following", fields: [followerId], references: [id])
followerId String
following User @relation("follower", fields: [followingId], references: [id])
followingId String
@@id([followerId, followingId])
}
model Post {
id Int @id @default(autoincrement())
title String
authorId String
author User @relation("author", fields: [authorId], references: [id])
likedBy User[] @relation(references: [id])
}
To get all unliked posts from followed users:
const posts = await prisma.post.findMany({
where: {
likedBy: {
none: {
id: 'cl3g1s5a20011llvcsllnzlra', // same as followerId
},
},
author: {
followers: {
some: {
followerId: 'cl3g1s5a20011llvcsllnzlra',
},
},
},
},
});
some
: Returns all records where one or more ("some") related records match filtering criteria.
https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#some
none
: Returns all records where zero related records match filtering criteria.- You can use
none
without parameters to return all records with no relations
- You can use
https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#none