保存嵌入式对象(包含用户的项目,例如用户,例如用户必须将项目ID作为外键)。
假设我们在nodejs quelize中具有这样的结构。
var User = sequelize.define('user', {/* ... */})
var Project = sequelize.define('project', {/* ... */})
Project.hasMany(User)
在视频主持人的这一部分中,旨在使用承诺以两个步骤保存嵌入式对象。在我们的情况下,这将是:
Project.create({
...
}).then(function(project){
User.create({
...
projectId:project.id
})
})
但是这种方法将导致两个 db调用。
因此,是否可以使用一个DB调用或使用sequelize?
您应该能够通过将一系列对象传递到与"include"
上使用的"as"
值相同的键来插入父子。尽管该文档对用法很亮,但您可以在此处看到它在源代码中进行处理。
没有承诺(puin semi-tristended),这是实际上在单个SQL查询中运行的,不确定续集中的确切实现。您应该能够启用记录(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));