2014-07-23 50 views
1

在Sequelize.js中構建和保存時,是否可以指定一個數組或必須在單獨的後續構建中完成?Sequelize:構建和保存包含數組的對象

模型定義:

var Tag = sequelize.define('Tag', { 
    name: Sequelize.STRING 
}); 

var Event = sequelize.define('Event', { 
    name: Sequelize.STRING, 
}); 

Event.hasMany(Tag, {as: 'tags', through: 'event_tags', foreignKey: 'eventId'}); 
Tag.hasMany(Event, {as: 'events', through: 'event_tags', foreignKey: 'tagId'}); 

什麼我問的是,如果這是可能的:

Event.build({ 
    name: 'blah', 
    tags: [{id: 53, name: someTag}, {id: 54, name: otherTag}] 

}).save().success(function(event) {...}); 

如果這是不可能的,我必須爲每個eventTag協會進行構建?

Event.build({ 
    name: 'blah', 

}).save().success(function(event) { 

    // ...How? because the association (table event_tags) is not an entity 
    // from which I could run .build() 
    // Maybe using push? 
}); 

回答

2

從sequelize文檔:Sequelize Associating Objects

Event.hasMany(Tag) 
Tag.hasMany(Event) 

Event.create()... 
Tag.create()... 
Tag.create()... 

// save them... and then: 
event.setTags([tag1, tag2]).success(function() { 
    // saved! 
}) 

在哪裏創建()'聯合建立()和save()。