sequelize fetching associations on find (1.6)

帅比萌擦擦* 提交于 2019-12-21 03:38:21

问题


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?


回答1:


BTW: Now that Sequelize 1.6.0 is out, the syntax for the eager loading has slightly changed:

User.find({ where: {id: id}, include: [Media] }).success(function(user){ 
  console.log(user.media)
})

So you'll have to pass the Model instead of the Model's name to the include statement.




回答2:


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)
})



回答3:


The answer is currently only available inside the code, the tests and ... my head :D

User.find({ where: {id: id}, include: ['Media'] }).success(function(user){ 
  console.log(user.media)
})

The reason for the not yet available documentation iiiiiis the fact, that the release is currently an alpha version.



来源:https://stackoverflow.com/questions/13002873/sequelize-fetching-associations-on-find-1-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!