Alvin
Alvin

Reputation: 8499

sequelize transaction cannot insert because of foreign key?

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.

Upvotes: 1

Views: 2163

Answers (1)

Dylan Aspden
Dylan Aspden

Reputation: 1692

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 :)

Upvotes: 1

Related Questions