Search code examples
javascriptmysqlmodelsequelize.jsbelongs-to

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


I have the following model:

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

I then try to create a row, after receiving userId, keyType and key:

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

The row gets created successfully in the DB, and i get back an ID (the createdAt and updatedAt are updated as well), but the userId is null.

How should I pass it to the create method so the value gets to the DB? Am I missing something in the model?

PS: the DB is MySQL 8.


Solution

  • I think you should change your code like below.

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