Hey everyone, I'm trying to display a many to many...
# orm-help
a
Hey everyone, I'm trying to display a many to many relation (I guess it's one to many in this one) for a GET request. Is there a better way of doing it other than searching the db twice? How would I chain the .resources() call to the first function?
Copy code
app.get(`/projects/:id`, async (req, res) => {
   const { id } = req.params;
   const project = await prisma.project.findOne({
      where: {
         id: Number(id),
      },
   });
   const resourcesOfProject = await prisma.project
      .findOne({ where: { id: Number(id) } })
      .resources();
   res.status(200).json({ ...project, resources: resourcesOfProject });
});

// Here is some of my schema
model Resource {
  id          Int       @default(autoincrement()) @id
  name        String
  description String?
  projects    Project[] @relation(references: [id])
}

model Project {
  id          Int        @default(autoincrement()) @id
  name        String
  description String?
  tasks       Task[]
  resources   Resource[] @relation(references: [id])
  completed   Boolean    @default(false)
}
m
I've been working with figuring out include statements (you can see that in my post right above yours). Try
Copy code
prisma.project.findOne({
      where: {
         id: Number(id),
      },
      include: {resources: true}
})
I'm still a noob so hopefully I didn't mess up the syntax
a
@Matt that worked, thanks!
👍 3