有没有办法使用 Sequelize 一次在 db 中保存多个嵌入式模型

Ser*_*b_b 2 javascript transactions node.js sequelize.js

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

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

Project.hasMany(User)
Run Code Online (Sandbox Code Playgroud)

视频演示者的这一部分中,使用 Promise 分两步保存嵌入的对象。在我们的例子中,它类似于:

Project.create({
  ...
  }).then(function(project){
     User.create({
        ...
        projectId:project.id
     })
   })
Run Code Online (Sandbox Code Playgroud)

但是这种方法会导致两次db 调用。

那么,是否可以通过一次数据库调用或在使用 Sequelize 的事务中将嵌入对象(包含用户的项目,例如用户必须将项目的 id 作为外键)保存到数据库中?

dou*_*arp 5

您应该能够通过传递对象的数组与同名的一键插入父子"as"所使用的价值"include"。尽管文档对用法的说明很简单,但您可以在此处源代码中看到它的处理。

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

// 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));
Run Code Online (Sandbox Code Playgroud)