sequelize transaction cannot insert because of foreign key?

旧街凉风 提交于 2019-12-11 14:46:29

问题


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);
            });

Why? From the log I can see the 2 sql insert statement, but it does not run commit.


回答1:


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);
  });

Good luck :)



来源:https://stackoverflow.com/questions/45615767/sequelize-transaction-cannot-insert-because-of-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!