Home > front end >  Prisma not liked posts from followed users
Prisma not liked posts from followed users

Time:05-22

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:

  1. The relation in Follows table seemed reversed, (i.e. followerId should be mapped to the following relation on the User model
  2. I assume each post is made by a user, so I added the author field in the Post model
  3. autoincrement() uses Int type, so cuid() is used instead in User 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

https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#none

  • Related