NodeJS TypeORM中的复合主键创建重复列

lsmd5eda  于 2023-04-05  发布在  Node.js
关注(0)|答案(1)|浏览(119)

我正在尝试创建一个名为“classes”的表,它充当两个表之间的链接,“user”和“class_group”。我想在“classes”中创建三个主键,它们也是外键。其中两个键应该来自“user”表的“id”列,并命名为“student_id”和“teacher_id”。第三个键应该来自“class_group”的“id”列表,并命名为“class_id”。
为此,我在“classes”实体中创建了“多对一”关系,在“user”和“class_group”实体中创建了“一对多”关系。然而,我最终在“classes”表中有六列而不是三列,我怀疑我在实现中犯了一个错误。
有人能帮我找出哪里出错了吗?

@Entity()
export class Classes {
  @PrimaryColumn()
  classId: number;

  @PrimaryColumn()
  studentId: number;

  @PrimaryColumn()
  teacherId: number;

  @ManyToOne(() => User, user => user.classes)
  @JoinColumn({ name: 'student_id' })
  student: User;

  @ManyToOne(() => User, user => user.classes)
  @JoinColumn({ name: 'teacher_id' })
  teacher: User;

  @ManyToOne(() => ClassGroup, classGroup => classGroup.classes)
  @JoinColumn({ name: 'class_id' })
  classGroup: ClassGroup;
}

@Entity()
export class User {
  ...

  @OneToMany(() => Classes, classes => classes.student)
  classes: Classes[];

  @OneToMany(() => Classes, classes => classes.teacher)
  classesAsTeacher: Classes[];
}

@Entity()
export class ClassGroup {
  ...

  @OneToMany(() => Classes, classes => classes.classGroup)
  classes: Classes[];
}
ev7lccsx

ev7lccsx1#

我只是复制了你的类定义如下:

@Entity()
export class Classes {
  @PrimaryColumn()
  classId: number;

  @PrimaryColumn()
  studentId: number;

  @PrimaryColumn()
  teacherId: number;

  @ManyToOne(() => User, user => user.classes)
  @JoinColumn({ name: 'student_id' })
  student: User;

  @ManyToOne(() => User, user => user.classes)
  @JoinColumn({ name: 'teacher_id' })
  teacher: User;

  @ManyToOne(() => ClassGroup, classGroup => classGroup.classes)
  @JoinColumn({ name: 'class_id' })
  classGroup: ClassGroup;
}

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(() => Classes, (classes) => classes.student)
  classes: Classes[];

  @OneToMany(() => Classes, (classes) => classes.teacher)
  classesAsTeacher: Classes[];
}

@Entity()
export class ClassGroup {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(() => Classes, (classes) => classes.classGroup)
  classes: Classes[];
}

这段代码可以根据你的需要生成所有的表,见下图:

所以可能是TypeOrm版本,请检查代码,看看有什么区别。
希望对你有帮助

相关问题