【问题标题】:Many-To-One using Sequelize and NestJs使用 Sequelize 和 NestJs 的多对一
【发布时间】:2023-03-25 05:06:01
【问题描述】:

我正在尝试建立多对一关系(每个Book 有一个Category,但有很多Book 具有相同的Category)。

Nest 总是抛出这个错误:[ExceptionHandler] Foreign key for "Book" is missing on "Category".

为什么我的 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
}

谢谢

【问题讨论】:

    标签: typescript sequelize.js nestjs decorator


    【解决方案1】:

    已解决, 我这样做是为了让 Category 有一个 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[]
    }
    

    现在按预期工作

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2022-12-15
      • 2020-11-14
      • 2021-06-28
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多