Sequelize: Put child of the child data related from parent model into parent attribute

Viewed 55

Given:

Tables:

  • Table Students
  • Table Courses
  • Table Departments

Table relations (simplified):

  1. Students and Courses
  • Courses has many Students
  • Student belongs to many Majors
  1. Courses and Departments
  • Departments has many Courses
  • Courses belongs to Departments

Expected result:

[{
    'student_id': 12345,
    'student_name': 'Ifa',
    'courses': [{
        'courses_id': 2,
        'name': 'Information Technology'
     }],
    'departments': [{
        'department_id': 5,
        'name': 'Computer'
     }]
}]

Now result:

[{
    'student_id': 12345,
    'student_name': 'Ifa',
    'courses': [{
        'courses_id': 2,
        'name': 'Information Technology'
        'departments': [{
             'department_id': 5,
             'name': 'Computer'
         }]
     }],
}]

What i've tried:

const students = await Student.findAll({ 
    attributes: [
        'uuid',
        'email',
        'gender',
        'age',
    ],
    include: [{
        model: Course,
        as: 'courses',
        attributes: [
            'uuid',
            'name',
            'description',
        ],
        through: {
            attributes: []
        },
        include: [Department]
    }
    where: { 
        uuid: uuid, 
    },
});

Question: How to put 'department' data that related to students' (enrolled) courses to student's attribute?

0 Answers
Related