sports
sports

Reputation: 8147

Sequelize: building and saving an object that contains an array

When building and saving, in Sequelize.js, is it possible to specify an array or that must be done in a separate sequelize build?

Model definition:

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

What I'm asking is if this is possible:

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

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

If this is not possible, I have to do a build for each of the eventTag associations?

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

Upvotes: 1

Views: 1488

Answers (1)

ilaif
ilaif

Reputation: 348

From the sequelize documentation: 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!
})

Where 'create()' combines build() and save().

Upvotes: 2

Related Questions