gpt4 book ai didi

javascript - 一次性创建记录和关联记录

转载 作者:搜寻专家 更新时间:2023-10-30 23:38:44 26 4
gpt4 key购买 nike

问题:

假设我有两个关联模型,Library有很多 Book:

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

最佳答案

您可以通过向创建参数添加 include 选项来实现您想要的行为,如下所示:

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

关于javascript - 一次性创建记录和关联记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37892699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com