Search code examples
typescriptdatabasesequelize.jsforeign-keyssequelize-typescript

One-to-one in sequelize-typescript with multiple foreign keys


My question is, how can I add multiple foreign keys to an object. I have an example with Complaint. And contains 2 Transports. One to track the goods being sent back and one to track the goods being sent again to the customer.

@Table({ tableName: "transport" })
export class Transport extends Model {

    @Column
    trackingNumber?: string;
}


export class Complaint extends Model {

    @ForeignKey(() => Transport)
    returnGoodsTransportId!: bigint;

    @BelongsTo(() => Transport)
    returnGoodsTransport!: Transport;

    @ForeignKey(() => Transport)
    resendGoodsTransportId!: bigint;

    @BelongsTo(() => Transport)
    resendGoodsTransport!: Transport;
}

For this purposes I removed my unnecessary code from the model.

With this example I only end up with only one Foreign key in the database. The first one in the Complaint.

I am expecting both foreign keys in the db table


Solution

  • I solved it in case anybody faces this problem.

    I found the answer here: https://github.com/sequelize/sequelize-typescript/issues/266

    I had to link my "belongTo" to my FK, because otherwise belongTo didnt know which FK to take so it took the first one.