【问题标题】:Sequelize: building and saving an object that contains an arraySequelize:构建并保存包含数组的对象
【发布时间】:2026-02-13 16:55:02
【问题描述】:

在 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?
});

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    来自续集文档: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()。

    【讨论】: