T
T
Timur Evgazhukov2021-08-24 13:29:24
PostgreSQL
Timur Evgazhukov, 2021-08-24 13:29:24

Why, when requesting data through Sequelize, an error is generated that you need to specify an alias?

I use:
"sequelize": "^6.6.5",
"sequelize-typescript": "^2.1.0",

There is a company data model, which can be a child of another company and, accordingly, there is:

@ForeignKey(() => Company)
@Column({
    type: DataType.INTEGER
})
parentId: number;

@BelongsTo(() => Company, "parentId")
parent: Company;

@HasMany(() => Company, "parentId")
subsidiaries: Company[];


Through migration I add to the database:
"parentId": {
          "onDelete": "NO ACTION",
          "onUpdate": "CASCADE",
          "references": {
            "model": "companies",
            "key": "id"
          },
          "allowNull": true,
          "type": Sequelize.INTEGER
        },


Everything is fine in the database:
6124c9bef2da9638045032.png
6124c9f8375ba913318144.png

But when I request from the database through
const company = await Company.findByPk(companyId, { include: [{ model: Company, as: "parentId" }] });


An error is thrown:
Company is associated to Company multiple times. To identify the correct association, you must use the 'as' keyword to specify the alias of the association you want to include.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question