Sequelize Typescript 关联外键问题

时间:2021-05-03 11:13:36

标签: mysql node.js typescript sequelize.js

我使用 MS SQL 实现了 Sequelize TypeScript 数据库 ORM。插入查询和更新查询工作正常。在获取数据时,我尝试关联模型但它抛出错误:

error - message: Foreign key for \"ScheduleModel\" is missing on \"EventModel\"

父表:schedule

export interface ScheduleAttribute {
  name: string;
  eventId: string;
  notes: string;
  events: EventAttributes[];
  createdBy: string;
}
export interface CreateScheduleAttributes extends Omit<ScheduleAttribute, 'id'> {}

@ObjectType({ simpleResolvers: true })
@Table({
  tableName: 'schedule',
})

export class ScheduleModel extends Model<ScheduleModel> implements ScheduleAttribute {
  @PrimaryKey
  @Field(() => ID)
  @Column({ defaultValue: DataType.UUIDV4 })
  id: string;

  @Field({ nullable: false })
  @Column({ field: 'name', allowNull: false })
  name: string;

  @PrimaryKey
  @Field(() => String, { nullable: true })
  @ForeignKey(() => EventModel)
  @Column
  eventId: string;

  @Field(type => [EventModel])
  @HasMany(()=>EventModel)
  events: EventModel[];

  @Field({ nullable: true })
  @Column({ field: 'createdBy', allowNull: true })
  createdBy: string;
} 

子表:

export interface EventAttributes {
  eventname: string;
  eventDate: string;
  eventType: string;
}
export interface CreateEventAttribute extends Omit<EventAttributes, 'id'> {}

@ObjectType({ simpleResolvers: true })
@Table({
  tableName: 'events',
})

export class EventModel extends Model<EventModel> implements EventAttributes {
  @PrimaryKey
  @Field(() => ID)
  @Column({ defaultValue: DataType.UUIDV4 })
  id: string;

  @Field({ nullable: false })
  @Column({ field: 'eventname', allowNull: false })
  eventname: string;

    @Field({ nullable: false })
  @Column({ field: 'eventDate', allowNull: false })
  eventDate: string;

    @Field({ nullable: false })
  @Column({ field: 'eventType', allowNull: false })
  eventType: string;

  @BelongsTo(() => ScheduleModel, { foreignKey: 'eventId' })
  events: ScheduleModel;
}

插入查询工作正常。当尝试获取记录时,它会抛出以下错误:

error - message: Foreign key for \"ScheduleModel\" is missing on \"EventModel\"

我写了以下 GetAPI:

sObj = await ScheduleModel.findAll({
  include: [
    {
      model:  EventModel,
    },
  ]
});
return sObj

请帮助一些人解决它。提前致谢。

1 个答案:

答案 0 :(得分:0)

至少你需要在两边用相同的值表示相同的foreignKey选项:

export class ScheduleModel extends Model<ScheduleModel> implements ScheduleAttribute {
// other fields here
  @Field(type => [EventModel])
  @HasMany(()=>EventModel, { foreignKey: 'eventId' })
  events: EventModel[];
// other fields here