如何在 Sequelize 中更新外键 (belongsTo)

How do I update a foreign key (belongsTo) in Sequelize

我有以下型号:

'use strict';
const {Model} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Key extends Model {
    static associate(models) {
      Key.belongsTo(models.User, {
        foreignKey: 'userId',
        onDelete: 'CASCADE'
      });
    }
  };
  Key.init({
    keyType: DataTypes.STRING,
    key: DataTypes.JSON
  }, {
    sequelize,
    modelName: 'Key',
  });
  return Key;
};

然后我尝试在收到 userIdkeyTypekey 后创建一行:

...
const Key = KeyModel(sequelize, Sequelize);
const createKey = async (userid, keyType, key) => {
  const result = await Key.create({userId, keyType, key});
  return result;
}

该行在数据库中成功创建,我得到一个 ID(createdAtupdatedAt 也更新),但 userId 为空。

我应该如何将它传递给 create 方法以便将值传递给数据库?我是否遗漏了模型中的某些内容?

PS: 数据库是 MySQL 8.

我认为你应该像下面这样更改你的代码。

'use strict';
const {Model} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Key extends Model {
    static associate(models) {
      Key.belongsTo(models.User, {
        foreignKey: 'keyId',
        targetKey: 'userId'
        onDelete: 'CASCADE'
      });
    }
  };
  Key.init({
    keyId: DataTypes.STRING,
    keyType: DataTypes.STRING,
    key: DataTypes.JSON
  }, {
    sequelize,
    modelName: 'Key',
  });
  return Key;
};

const Key = KeyModel(sequelize, Sequelize);
const createKey = async (userId, keyType, key) => {
  const result = await Key.create({keyId: userId, keyType, key});
  return result;
}