Sequelize:构建和保存包含数组的对象

时间:2014-07-23 19:12:35

标签: node.js sequelize.js

在构建和保存时,在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?
});

1 个答案:

答案 0 :(得分: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!
})

其中'create()'结合了build()和save()。