Eagerly Loaded Associations on sequelize

Problem

I have the following entities:

var Group = sequelize.define("Group", { name: Sequelize.STRING });
var Course = sequelize.define("Course", { name: Sequelize.STRING });
var GroupHasCourse = sequelize.define("GroupHasCourse", { name: Sequelize.STRING });
var Student = sequelize.define("Group", {   name: Sequelize.STRING });

And the following associations:

Course.hasMany(GroupHasCourse, { as: "GroupsOnCourses"});
Group.hasMany(GroupHasCourse, { as: "CoursesOnGroups"});
GroupHasCourse.hasMany(Student, { as: "Students"});

Two questions:

  1. Is this the best way to do the association between the Group-Course relationship in order to get students into the subjets?
  2. I'm doing the following query:

    Course.findAll({include:[{model:GroupHasCourse, as:"GroupsOnCourses"}]}).success(function(courses){
        // courses[0].groupsOnCourses[0].GroupId
    })
    

    How can I get also the left join in that query so I dont need to do another query having

    Group.find(courses[0].groupsOnCourses[0].GroupId)
    
Problem courtesy of: Dan Rocha

Solution

So this already works with 1.6.0:

var Sequelize = require('sequelize')
var sequelize = new Sequelize('sequelize_test', 'root')

var Group = sequelize.define("Group", { name: Sequelize.STRING })
var Course = sequelize.define("Course", { name: Sequelize.STRING })
var GroupHasCourse = sequelize.define("GroupHasCourse", { name: Sequelize.STRING })
var Student = sequelize.define("Group", {   name: Sequelize.STRING })

Course.hasMany(GroupHasCourse, { as: "GroupsOnCourses"})
Group.hasMany(GroupHasCourse, { as: "CoursesOnGroups"})
GroupHasCourse.hasMany(Student, { as: "Students"}).belongsTo(Group).belongsTo(Course)

sequelize.sync({ force: true }).success(function() {
  Group.create({ name: 'group' }).success(function(group) {
    Course.create({ name: 'course' }).success(function(course) {
      GroupHasCourse.create({ name: 'bla' }).success(function(groupHasCourse) {
        groupHasCourse.setGroup(group).success(function() {
          groupHasCourse.setCourse(course).success(function() {
            GroupHasCourse.findAll({
              include: [ Group, Course ]
            }).success(function(groupHasCourses) {
              console.log(groupHasCourses[0].values)
            })
          })
        })
      })
    })
  })
})
Solution courtesy of: sdepold

Discussion

do you need the join table for further data or are you just connecting Corse and Group? If you just want to connect them you can do this:

Course.hasMany(Group)
Group.hasMany(Course)

This will create the join table for you automagically. If you want that way, your next will be, that you wait for a first alpha/beta/whatever of Sequelize 1.6.1 which will support eager loading for many-to-many associations. The version will be available during the week.

Greetings, sdepold

Discussion courtesy of: sdepold

This recipe can be found in it's original form on Stack Over Flow.