Multiple relation in Sequelize typescript | Arshnoor Singh

Multiple relation in Sequelize typescript

Multiple relations of same models

sequelize-typescript resolves the foreign keys by identifying the corresponding class references.

So if we define a model with multiple relations like

class Book extends Model { @ForeignKey(() => Person) @Column authorId: number; @BelongsTo(() => Person) author: Person; @ForeignKey(() => Person) @Column proofreaderId: number; @BelongsTo(() => Person) proofreader: Person;}@Tableclass Person extends Model { @HasMany(() => Book) writtenBooks: Book[]; @HasMany(() => Book) proofedBooks: Book[];}

Sequelize-typescript cannot know which foreign key to use for which relation.

So we have to add the foreign keys explicitly:

// in class "Books": @BelongsTo(() => Person, 'authorId') author: Person; @BelongsTo(() => Person, 'proofreaderId') proofreader: Person; // in class "Person": @HasMany(() => Book, 'authorId') writtenBooks: Book[]; @HasMany(() => Book, 'proofreaderId') proofedBooks: Book[];

Type safe usage of auto generated functions

With the creation of a relation, sequelize generates some method on the corresponding models.

So when we create a 1:n relation between ModelA and ModelB, an instance of ModelA will have the functions getModelBs, setModelBs, addModelB, removeModelB, hasModelB.

These functions still exist with sequelize-typescript.

But TypeScript wont recognize them and will complain if you try to access getModelB, setModelB or addModelB.

To make TypeScript happy, the Model.prototype of sequelize-typescript has $set, $get, $add functions.