sequelize-typescript: Alias cannot be inferred

Given the following models, each of the associations work fine in isolation but not if used together. I’m getting:

Error: Alias cannot be inferred: “Estimate” has multiple relations with “Employee”

What am I doing wrong?

@Table()
export default class Estimate extends Model<Estimate> {

  // Fields....

  @ForeignKey(() => Employee) @Column estimatorId: number;
  @BelongsTo(() => Employee) estimator: Employee;

  @ForeignKey(() => Employee) @Column foremanId: number;
  @BelongsTo(() => Employee) foreman: Employee;

  @BelongsToMany(() => Employee, () => Crew) crew: Employee[];
}
@Table()
export default class Employee extends Model<Employee> {

  // Fields....

  @HasMany(() => Estimate, 'estimatorId') estimatesAsEstimator: Estimate[];
  @HasMany(() => Estimate, 'foremanId') estimatesAsForeman: Estimate[];

  @BelongsToMany(() => Estimate, () => Crew) estimatesAsCrew: Estimate[];
}
@Table()
export default class Crew extends Model<Crew> {

  @ForeignKey(() => Employee) @Column employeeId: number;
  @ForeignKey(() => Estimate) @Column estimateId: number;

}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 22 (12 by maintainers)

Commits related to this issue

Most upvoted comments

@doovers Does the error happen while initializing these models or when trying to retrieve data? If it happens when retrieving data, you also need to define what exact include do you want to use. Therefor you have to set as explicitly like:

Employee.findAll({
  include: [{model: Estimate, as: 'estimatesAsEstimator'}]
})

@RobinBuschmann Apologies for the late reply! I had another look at this and it happens when I call create on a model that BelongsTo a model with include: [{ all: true }]

Logging include at /node_modules/sequelize/lib/model.js:465:29 yields:

  static _validateIncludedElement(include, tableNames, options) {
    console.log(include);
    tableNames[include.model.getTableName()] = true; // Fails here
{
    "all": true,
    "parent": {
        "model": "Employee",
        "as": "estimator",
        "association": "estimator",
	...
    }
}

Note that the model attribute is missing where all: true but in the parent it is present.