问题:
想象一下,我有两个关联的模型,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
});
});
问题:
是否可以一次性创建Library
和Book
个实例 - 进行单create()
次呼叫?
类似的东西(更像是伪代码):
Library.create({
name: 'Roan Library',
address: '123 Any St',
books: [
{
title: 'Reading with Time',
description: 'A fun jaunt in reading',
libraryId: library.id
}
]
});
答案 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]
});