Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Foreign key for x missing on y" #1585

Closed
1 task
0tii opened this issue Feb 20, 2023 · 0 comments
Closed
1 task

"Foreign key for x missing on y" #1585

0tii opened this issue Feb 20, 2023 · 0 comments

Comments

@0tii
Copy link

0tii commented Feb 20, 2023

Issue

Making simple associations is proving borderline impossible without modifying the (existing) db- / table-structure.

Versions

  • sequelize: 6.28.0
  • sequelize-typescript: 2.1.5
  • typescript: 4.7.4

Issue type

  • [x ] bug report
  • feature request

Actual behavior

I have two tables, Product and Supplier. In Product there is a column supplier_id which is a FK to supplier.id. However, whatever I am trying, this simple association does not work, giving me an Error 'Error: Foreign key for "Product" is missing on "Supplier".'.

Expected behavior

Not give me an error and create a simple foreign key Product.supplier_id referencing Supplier.id.

Steps to reproduce

Creating those model classes and trying to sync them.

Related code

Product Model

@Table({
  timestamps: true,
  tableName: "product",
})
export class Product extends Model {
  @Column({
    type: DataType.STRING(8),
    allowNull: false,
    primaryKey: true
  })
  id!: string;

  @HasOne(() => Supplier)
  @Column({
    type: DataType.STRING(8),
    allowNull: false,
  })
  supplier_id!: Supplier;
}

Supplier Model

@Table({
  timestamps: true,
  tableName: "supplier",
})
export class Supplier extends Model {

  @ForeignKey(() => Strain)
  @Column({
    type: DataType.STRING(8),
    allowNull: false,
    primaryKey: true,
    unique: true
  })
  id!: string;

It really doesn't matter how and in which order I decorate the respective fields, using @BelongsTo, @HasMany, @HasOne, @ForeignKey, it always spits out the same error Error: Foreign key for "Product" is missing on "Supplier"..

Solution

As it always is, once you create an issue / open a thread about a problem, you find the solution yourself. In this case I had an oversight in reading the docs and threads on SO and in the issues.

In order to declare associations per Foreign Key, the target Model needs a property of the source Model type, but not as a column.

In my case it was

  @HasMany(() => Product)
  products!: Product[]
@0tii 0tii closed this as completed Feb 20, 2023
@0tii 0tii changed the title Associations are an absolute mess? "Foreign key for x missing on y" "Foreign key for x missing on y" Feb 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant