PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

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

 July 26, 2022     belongs-to, javascript, model, mysql, sequelize.js     No comments   

Issue

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


Answered By - niour
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing