我有三种模式:
var Person = sequelize.define("Person", {
no: {type: DataTypes.STRING, unique: true, allowNull: false}
}, {
classMethods: {
associate: function(models){
Person.hasMany(models.Task);
Person.hasMany(models.Job);
}
}
});
Task has field: description, and Job has field: title.
现在我尝试使用事务来插入记录,但我被卡住了:
return sequalize.transaction(function (t) {
return models.Person.create({
no: '1221212'
}, {transaction: t}).then(function (person){
// I am stuck here, to insert multiple task and job
}, {transaction: t});
}).then(function(result){
}).catch(function(err){
});
如何在创建人员后插入multiple
任务和工作?
答案 0 :(得分:1)
您可以像这样创建子对象:
return sequelize.transaction(function (t) {
return Person.create({
no: '1221212',
Tasks: [
{ taskName: 'task1' },
{ taskName: 'task2' }
]}, {
transaction: t,
include: [ { model: Task } ]
}
);
});
我们使用" include"选项在这里。
这是SQL生成的:
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): START TRANSACTION;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): SET autocommit = 1;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "People" ("id","no") VALUES (DEFAULT,'1221212') RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'task1',3) RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'task2',3) RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): COMMIT;
您还可以创建一个Person,然后批量添加任务。如果任务数量很大,这将很有效,因为它只对所有任务使用一个INSERT操作。
return sequelize.transaction(function (t) {
return Person.create({
no: '00000'
}, {
transaction: t,
})
.then(function(person) {
return Task.bulkCreate( [
{ taskName: 't1', PersonId: person.id },
{ taskName: 't2', PersonId: person.id }
], {
transaction: t
});
});
});
我们使用bulkCreate函数并手动设置外键字段的id。 这将生成以下SQL:
Executing (c9802841-6a22-4633-a006-41a78a9623b2): START TRANSACTION;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): SET autocommit = 1;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): INSERT INTO "People" ("id","no") VALUES (DEFAULT,'00000') RETURNING *;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'t1',4),(DEFAULT, 't2', 4)
Executing (c9802841-6a22-4633-a006-41a78a9623b2): COMMIT;