Search code examples
typescriptsequelize.jsnestjsdecorator

Many-To-One using Sequelize and NestJs


I'm trying to make a Many-To-One relation (each Book has one Category, but there are many Book with the same Category).

Nest always throws this error: [ExceptionHandler] Foreign key for "Book" is missing on "Category".

Why do I need a foreign key in my Category model ? Isn't it supposed to be the opposite, the Book that have a foreign key for the Category?

book.model.ts

@Table({tableName: 'BOOK'})
export class Book extends BaseModel<Book> {

    ... some fields
    
    @ForeignKey(() => Category)
    @Column({field: 'CATEGORY_ID'})
    categoryId: number // Category ID stored in my Database

    @HasOne(() => Category)
    category: Category    
}

category.model.ts

@Table({tableName: 'CATEGORY'})
export class Category extends BaseModel<Category> {
    @Column({field: 'NAME'})
    name: string

    @BelongsTo(() => Book)
    book: Book
}

base.model.ts

export class BaseModel<T> extends Model<T> {
    @Column({field: 'ID', primaryKey: true, autoIncrement: true, type: DataType.BIGINT })
    id: number;

    ... some other stuff
}

Thank you


Solution

  • Solved, I made it so the Category has a list of Book.

    book.model.ts

    @Table({tableName: 'BOOK'})
    export class Book extends BaseModel<Book> {
    
        ... some fields
        
        @ForeignKey(() => Category)
        @Column({field: 'CATEGORY_ID'})
        categoryId: number // Category ID stored in my Database
    
        @BelongsTo(() => Category)
        category: Category    
    }
    

    category.model.ts

    @Table({tableName: 'CATEGORY'})
    export class Category extends BaseModel<Category> {
        @Column({field: 'NAME'})
        name: string
    
        @HasMany(() => Book)
        book: Book[]
    }
    

    Now working as expected