Define Many-to-Many associations
masterUse @BelongsToMany on both participating models. You must provide a through-table model as the second argument to the decorator. To access the through-table instance type-safely, you must manually define the type using an intersection type.
@Table
class Book extends Model {
@BelongsToMany(() => Author, () => BookAuthor)
authors: Author[];
}
@Table
class Author extends Model {
@BelongsToMany(() => Book, () => BookAuthor)
books: Book[];
// Type safe access to the through-table instance
@BelongsToMany(() => Book, () => BookAuthor)
booksWithThrough: Array<Book & {BookAuthor: BookAuthor}>;
}
@Table
class BookAuthor extends Model {
@ForeignKey(() => Book)
@Column
bookId: number;
@ForeignKey(() => Author)
@Column
authorId: number;
}