由于外键,sequelize 事务无法插入? [英] sequelize transaction cannot insert because of foreign key?
本文介绍了由于外键,sequelize 事务无法插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用sequelize事务插入2张表,user和job,每个user有一个job,userId为job表中的外键:
Using sequelize transaction to insert into 2 tables, user and job, each user has one job, userId is the foreign key in job table:
sequelize.transaction(function(t) {
return models.users.create({
userType: 'test',
username: 'alvin',
}, {transaction: t}).then(function(user) {
return models.job.create({
jobType: 'jocker',
userId: user.userId // Take away this will work, it is a foreign key
});
}, {transaction: t});
}).then(function(result) {
resolve(result);
}).catch(function(err) {
reject(err);
});
为什么?从日志中我可以看到 2 sql insert 语句,但它没有运行 commit
.
Why? From the log I can see the 2 sql insert statement, but it does not run commit
.
推荐答案
您需要在同一个事务中创建作业.看起来您只是将创造就业的交易放在了错误的位置.像我在下面那样移动它应该可以解决您的问题.
You need to create the job in the same transaction. It looks like you just put the transaction for the job creation in the wrong spot. Moving it as I did below should fix your problem.
sequelize
.transaction(function(t) {
return models.users
.create(
{
userType: 'test',
username: 'alvin'
},
{ transaction: t }
)
.then(function(user) {
return models.job.create(
{
jobType: 'jocker',
userId: user.userId
},
{
transaction: t // <-- Second argument to .create
}
);
});
})
.then(function(result) {
resolve(result);
})
.catch(function(err) {
reject(err);
});
祝你好运:)
这篇关于由于外键,sequelize 事务无法插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文