0

I want to create a relationship between parents table and children table and this is how i doing it

// 20210226075430-create-child.js (children migration file)

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Children", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        type: Sequelize.STRING,
      },
      age: {
        type: Sequelize.STRING,
      },
      parentId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        onDelete: "CASCADE",
        references: {
          model: "Parents",
          key: "id",
        },
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Children");
  },
};

// parent migration file

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Parents", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        type: Sequelize.STRING,
      },
      age: {
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Parents");
  },
};

// child.js / children model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Child extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Child.belongsTo(models.Parent, { foreignKey: "parentId" });
    }
  }
  Child.init(
    {
      name: DataTypes.STRING,
      age: DataTypes.STRING,
      parentId: DataTypes.INTEGER,
    },
    {
      sequelize,
      modelName: "Child",
    }
  );
  return Child;
};

// parent model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Parent extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Parent.hasMany(models.Child);
    }
  }
  Parent.init(
    {
      name: DataTypes.STRING,
      age: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "Parent",
    }
  );
  return Parent;
};

this code perfectly fine in mysql but when i change dialect to postgres i got error like this :

Executing (default): SELECT "id", "name", "age", "parentId", "createdAt", "updatedAt", "ParentId" FROM "Children" AS "Child";
(node:7496) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "ParentId" does not exist
    at Query.formatError (D:\work\www\express-starter\node_modules\sequelize\lib\dialects\postgres\query.js:386:16)
    at Query.run (D:\work\www\express-starter\node_modules\sequelize\lib\dialects\postgres\query.js:87:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:7496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I have already tried to add foreign key in child.js (model) but i still got this error.

where i doing it wrong?

1 Answer 1

1

You didn't indicate parentId as a foreignKey option in the association from Parent to Children that's why Sequelize automatically generates its name like ParentId. Just indicate the same option and value as in belongsTo like this:

Parent.hasMany(models.Child, { foreignKey: "parentId" });
Sign up to request clarification or add additional context in comments.

3 Comments

Your right sir!, still wondering why in mysql there's no error like this..
Maybe MySQL processes column names as case insensitive?
maybe that's the case, anyway thanks sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.