有没有办法使用Sequelize一次性保存多个embedded式模型

假设我们在NodeJs Sequelize中有这样的结构。

var User = sequelize.define('user', {/* ... */}) var Project = sequelize.define('project', {/* ... */}) Project.hasMany(User) 

video演示者的这部分提供了使用承诺以两个步骤保存embedded的对象。 在我们的情况下,会是这样的:

 Project.create({ ... }).then(function(project){ User.create({ ... projectId:project.id }) }) 

但是这种方法会导致两个数据库调用。

那么,是否有可能保存embedded式对象(包含用户的项目,例如用户必须有项目的ID作为一个外键)到一个数据库调用数据库或在一个事务使用Sequelize?

您应该可以通过将一个对象数组传递给与"include"上使用的"as"值相同的名称来插入父项子项。 尽pipe这些文档很less使用,但您可以在这里看到它在源代码中的处理。

没有承诺(双关半意),这实际上是在单个SQL查询中运行,不确定在Sequelize中的确切实现。 您应该能够启用日志logging(在Sequelize(options) logging: console.log )来查看它正在运行的内容。

 // specify an "as" value and require a User.project_id value Project.hasMany(User, { as: 'Users', foreignKey: { allowNull: false } }); // define your Project -> Users as json with the "as" value as the key const project = { name: 'project name', Users: [ { name: 'user 1', }, { name: 'user 2', }, ], }; // create a transaction and "include" the Model in the create, txn falls back in .catch() sequelize.transaction(t => Project.create(project, { include: [{ model: User, as: 'Users', }], transaction: t, }) ) .catch(e => console.log('the txn failed because', e));