Sequelize: Insert failed to foreignKey column

Issue

I’m trying to insert data to my table with foreign keys from another table. The relationship is already successfully created. But when I try to insert data to the table, it always input null, and I already handle it with add allowNull: false. But still don’t know how to input the value into the foreign key value inside table column.

This is my Product model:

    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false
      },
      description: {
        type: DataTypes.TEXT,
        allowNull: true
      },
      price: {
        type: DataTypes.DECIMAL,
        allowNull: false,
        validate: {
          isNumeric: {
            args: true,
            msg: 'Wrong price format'
          }
        }
      },
      image: {
        type: DataTypes.TEXT,
        allowNull: false
      }
    },
    {
      sequelize,
      paranoid: true,
      modelName: 'product'
    }
  );

and this is my category model:

category.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false
      },
      image: {
        type: DataTypes.TEXT,
        allowNull: false
      }
    },
    {
      sequelize,
      paranoid: true,
      modelName: 'category'
    }
  );

and this is relationship between them

category.hasMany(product, {
  foreignKey: {
    name: 'categoryId',
    allowNull: false
  },
  onDelete: 'CASCADE'
});
product.belongsTo(category, {
  foreignKey: {
    name: 'categoryId',
    allowNull: false
  },
  onDelete: 'CASCADE'
});

and on inserting code using express, this is the code:

const product = {
    name,
    description,
    price,
    image,
    businessCompanyId,
    categoryId
  };

await Product.create(product);

Any help will be great, thank you!

Solution

Add a field of categoryId in Product model like this:-

categoryId: {
  type: DataTypes.UUID,
  allowNull: false,
  references: {
    model: "category",
    key: "id"
  }
},

I have not proper understanding of businessCompanyId but hope this will help you!

Answered By – Devashish Suthar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published