Hey, I am new to Prisma and trying to implement th...
# orm-help
r
Hey, I am new to Prisma and trying to implement the like feature on posts in my app. I am trying to follow the approach where every post will have likedBy model which will connect to the user who likes it. So how do I write a query to connect id of the user in likedBy every time someone like a post? just like this but query to add the user in likedBy https://prisma.slack.com/archives/CA491RJH0/p1595334595209500?thread_ts=1595333884.208000&cid=CA491RJH0
✅ 1
j
Copy code
prisma.post.update({
  where: { id },
  data: {
    postLikes: {
      create: { userId },
    },
  },
});
You can also do it via an implicit many<->many between Posts and Users, like this: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#connect-an-existing-record
So
create
for explicit relationship,
connect
for implicit relationship
r
Thanks. I tried your suggestion but keep getting this error. not sure what i am doing wrong
`Invalid
prisma.post.update()
invocation:`
{
where: {
?   id?: String
},
data: {
likedByUsers: {
create: {
id: 'cl6341sfa0006akiq5qbr'
}
}
}
}
Argument where of type PostWhereUniqueInput needs at least one argument. Available args are listed in green.
n
Could you share your schema file? Also could you check that the
id
being passed in the where cause of update query is correct and not
null
or
undefined
r
Copy code
model User {
  id            String    @id @default(cuid())
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
  name          String?
  email         String?   @unique
  password      String?
  emailVerified DateTime?
  image         String?
  role          String?   @default("user")
  accounts      Account[]
  sessions      Session[]
  posts         Post[]
   likedPosts    Post[]    @relation("likedPosts")
}

model Post {
  id       String   @id @default(cuid())
  created  DateTime @default(now())
  userName String?
  title    String?
  category String?
  author   User?    @relation(fields: [authorId], references: [id])
  authorId String?

  likedByUsers User[]    @relation("likedPosts")
  @@index([authorId])
}
these are the schema for post and user and the function to perform LIKE
Copy code
try {
            const body = { id };

            console.log(body)
            await fetch('/api/like', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
            });


        } catch (error) {
            console.error(error);
        }
I am sending the id, i can see it in payload. Not sure why its not reading in the next API route
Copy code
export default async function handle(req, res) {

  const session = await getSession({ req });
  const { id } = req.body;

  const { userId } = session;

const result = await prisma.post.update({
  where: {id},
  data: {
   likedByUsers: {
      create: { id:userId},
    },
  },
});
  res.json(result)
}
n
If you
console.log(req.body.id)
then are you getting the id in the log?
r
No i am not getting the id, even though I am passing it. i can't see othelogs too like tried console.log('ok'). now I am pretty sure the issue is with only id, can't seem to fix it
n
Yes, you would need to pass the id in order to update the post. Here’s a script where I am creating a user and a post and then updating the post to register a Like
Copy code
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: ['query'],
});

async function main() {
  await prisma.user.deleteMany();
  await prisma.post.deleteMany();

  const userId = 'cl66cp94a00015378llsicsp4';
  const postId = 'cl66crerw00129578qo29qenz';

  await prisma.user.create({
    data: {
      id: userId,
      email: 'sundarani@prisma.io',
      name: 'Sundarani',
      posts: {
        create: {
          id: postId,
          title: 'My first post',
        },
      },
    },
  });

  await prisma.post.update({
    where: {
      id: postId,
    },
    data: {
      likedByUsers: {
        connect: {
          id: userId,
        },
      },
    },
  });

  console.log('Finished Execution');
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
Here’s the output where
likedByUsers
shows the user who has liked the post:
r
Thank you so much. Finally fixed it. rather than destructuring the body like
Copy code
const {postId}= body
I passed directly as
Copy code
where{
id:req.body.postId
}
somehow fixed it. been stuck since yesterday. Thank you for your time.
🙌 1
Also, it would be great to have examples like you shared in Prisma docs, I know there are examples with
followers
and
following
but it
LIKE
example would be a nice addition
n
Thanks for the feedback, I’ll pass it to the docs team!