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

标签 javascript mysql model sequelize.js belongs-to

我有以下模型:

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

关于javascript - 如何在 Sequelize 中更新外键 (belongsTo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67259916/

相关文章:

javascript - 将文本与单选按钮对齐

mvvm - Silverlight/MVVM 设计 : what is my model and where to put the logic?

ruby-on-rails - ActiveSupport::关注和扩展mongoid模型

mysql - XAMPP + OSX + Virtualhosts + 在 httpd.conf 中更改用户 = phpmyadmin 创建数据库不工作

php - MySQL/PHP - 多层类别结构

jquery - 如何检查单选按钮

model - anaconda 和 Spyder 中的包加载错误

javascript - JS 正则表达式 : Parse urls with conditions

javascript - jQuery - 有人可以帮忙用 .ajaxComplete() 拼接 jQuery 代码吗?

javascript - React.js 和 HTML5 电子邮件验证