13

sequelize 1.6 在更新日志中有以下内容:

[FEATURE] 为 find 和 findAll 添加关联预取

问题是如何?

我定义了以下模型:

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

稍后当我获取这样的用户时:

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

User 实例没有列表媒体。我如何自动获取关联?

4

3 回答 3

28

顺便说一句:现在 Sequelize 1.6.0 已经发布,预加载的语法略有变化:

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

因此,您必须将模型而不是模型的名称传递给 include 语句。

于 2013-04-05T20:11:51.457 回答
6

sdepold 实际上编写了代码,但我相信他为 include 确定的语法是:

User.find({ where: {id: id}, include: ['Media'] }).success(function(user){ 
  console.log(user.media)
})
于 2012-12-29T05:48:16.890 回答
4

答案目前仅在代码、测试和......我的头脑中可用:D

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

尚未提供文档的原因 iiiiii 是该版本目前是 alpha 版本。

于 2012-10-22T06:07:52.770 回答