代码之家  ›  专栏  ›  技术社区  ›  Alvin

由于外键,sequelize事务无法插入?

  •  1
  • Alvin  · 技术社区  · 9 年前

    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 .

    1 回复  |  直到 9 年前
        1
  •  1
  •   Dylan Aspden    9 年前

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

    祝你好运:)