alecxe
alecxe

Reputation: 473873

Create a record and an associated record in one go

The Problem:

Imagine I have two associated models, Library which has many Books:

var Library = sequelize.define('Library', {
    title: Sequelize.STRING,
    description: Sequelize.TEXT,
    address: Sequelize.STRING
});
var Book = sequelize.define('Book', {
    title: Sequelize.STRING,
    description: Sequelize.TEXT,
    publish_date: Sequelize.DATE
});
Library.hasMany(Book);

Now, in order to create a Library and a single associated Book, I do:

Library.create({
    name: 'Roan Library',
    address: '123 Any St'
}).then(function (library) {
    Book.create({
        title: 'Reading with Time',
        description: 'A fun jaunt in reading',
        libraryId: library.id
    });
});

The Question:

Is it possible to create a Library and a Book instance in one go - in a single create() call?

Something like (more like a pseudo-code):

Library.create({
    name: 'Roan Library',
    address: '123 Any St',
    books: [
        {
            title: 'Reading with Time',
            description: 'A fun jaunt in reading',
            libraryId: library.id
        }
    ]
});

Upvotes: 1

Views: 130

Answers (1)

Steffen Langer
Steffen Langer

Reputation: 1193

Your desired behavior can be achieved by adding the include option to the create parameters like so:

Library.create({
    name: 'Roan Library',
    address: '123 Any St',
    Books: [
        {
            title: 'Reading with Time',
            description: 'A fun jaunt in reading'
        }
    ]
}, {
    include : [Book]
});

Upvotes: 1

Related Questions