Create a record and an associated record in one go

╄→гoц情女王★ 提交于 2019-12-11 05:49:51

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/37892699/create-a-record-and-an-associated-record-in-one-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!