codda
codda

Reputation: 1

Fetching many to many data from prisma findMany

Currently I am working with next.js crud prisma with many-to-many relation. I am able to create all the end point for my crud operation. Now I am working on connection it to the client side which would display student with the class that student is attending. I am able to map my students and display their name but I am struggling to display the classes they are attending. I think my model are correct since I am able to added classes for individual student but it could be my get end point which I set to includes all student with class.

My prisma model:

model Student {
  id             Int     @default(autoincrement()) @id
  firstName      String  
  lastName       String
  classes        CourseEnrollment[]
}

model Class {
  id             Int     @default(autoincrement()) @id
  name           String
  courseDetails  String?    
  members        CourseEnrollment[] 
}

model CourseEnrollment {
  studentId      Int
 student        Student  @relation(fields: [studentId], references: [id])
  classId        Int
  class          Class   @relation(fields: [classId], references: [id])
  @@id([studentId, classId])
}

Get endpoint: // Maybe use select instead of include?

export default async function handler(req, res){
try{
 const result = await prisma.student.findMany({
    include: {
  classes: true,
     },
        });
       res.status(200).json(result);
    } catch (error) {
  console.log(error);
    } 
}

My endpoint show:

{"id":13,"firstName":"John","lastName":"doe","classes":[{"studentId":13,"classId":9}]},

Student page where I map through all students:

    {data.map((student, id) => (
    <StudentCard key={id} student={student}/>
  ))}

Student Card taking in student prop:

const ClassCard = ({student}) => {
  return (
     <div className={styles.card}>
<div className={styles.card_wrapper}>
  <div className={styles.card_title}>
     <h3>{student.firstName}</h3>
     <h3>{student.lastName}</h3>
   </div>
   <div className={styles.student_card}>
     <h2>Class attending</h2>

 //I tried student.class.classId
     <h3>{student.class}</h3>
    </div>
  </div>
</div>

Upvotes: 0

Views: 953

Answers (1)

Raphael Etim
Raphael Etim

Reputation: 813

select allows us to select specific fields from a record. It allows us to return a limited subset of the fields instead of all the fields. Nested select allows us to include specific relation fields from a related record. include on the other hand allows us to return all relation fields. See the Prisma docs for in-depth examples of how select differs from include.

Upvotes: 1

Related Questions