alecxe alecxe - 5 months ago 16
Node.js Question

Create a record and an associated record in one go

The Problem:

Imagine I have two associated models,

Library
which has many
Book
s:

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

Answer

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]
});
Comments