一次创建记录和相关记录

时间:2016-06-18 02:29:54

标签: javascript sql node.js database sequelize.js

问题:

想象一下,我有两个关联的模型,Library 有很多 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);

现在,为了创建Library和单个关联的Book,我这样做:

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

问题:

是否可以一次性创建LibraryBook个实例 - 进行create()次呼叫

类似的东西(更像是伪代码):

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

1 个答案:

答案 0 :(得分:1)

您可以通过将include选项添加到create参数来实现所需的行为,如下所示:

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