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