Home > Mobile >  Sequelize: Insert failed to foreignKey column
Sequelize: Insert failed to foreignKey column

Time:07-25

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!

CodePudding user response:

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 bussinessCompanyId but hope this will help you!

  • Related