Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize fetching associations on find (1.6)

sequelize 1.6 has the following in the changelog:

[FEATURE] added association prefetching for find and findAll

The question is HOW?

I have the following models defined:

var self = {
    Medium: client.define("Medium", {
        name: Sequelize.STRING,
        description: Sequelize.TEXT
    },

    User: client.define("User", {
        firstName: Sequelize.STRING,
        lastName: Sequelize.STRING,
        email: Sequelize.STRING,
        aboutArt: Sequelize.TEXT,
        bio: Sequelize.TEXT,
        password: Sequelize.STRING,
        description: Sequelize.TEXT
    }
};
self.User.hasMany(self.Medium, { as: 'Media' });
self.Medium.hasMany(self.User);

for(var key in self){
    var model = self[key];
    model.sync();
}

later when i fetch a user like this:

 User.find(id)
    .success(function(record) {
        //record has no media!
    })

the User instance does not have a list media. How do i auto fetch associations?

like image 529
mkoryak Avatar asked Oct 21 '12 22:10

mkoryak


1 Answers

sdepold actually wrote the code, but I believe the syntax he settled on for include is:

User.find({ where: {id: id}, include: ['Media'] }).success(function(user){ 
  console.log(user.media)
})
like image 84
Dan Kohn Avatar answered Sep 28 '22 10:09

Dan Kohn