为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 TypeORM 中检索关联数据和关系数据?

如何在 TypeORM 中检索关联数据和关系数据?

哔哔one 2022-05-22 15:58:57
我有这个实体类。这是两个表之间的关联。import { Column, Entity, Index, JoinColumn, ManyToOne } from "typeorm";import { Classroom } from "./Classroom";import { Teacher } from "./Teacher";@Index("fk_class_has_teacher_teacher1_idx", ["teacherId"], {})@Index("fk_class_has_teacher_class1_idx", ["classId"], {})@Entity("teacherclassroom", { schema: "school" })export class Teacherclassroom {  @Column("int", { primary: true, name: "class_id" })  classId: number;  @Column("int", { primary: true, name: "teacher_id" })  teacherId: number;  @Column("datetime", {    name: "reg_date",    nullable: true,    default: () => "CURRENT_TIMESTAMP"  })  regDate: Date | null;  @ManyToOne(    () => Classroom,    classroom => classroom.teacherclassrooms,    { onDelete: "NO ACTION", onUpdate: "NO ACTION" }  )  @JoinColumn([{ name: "class_id", referencedColumnName: "id" }])  class: Classroom;  @ManyToOne(    () => Teacher,    teacher => teacher.teacherclassrooms,    { onDelete: "NO ACTION", onUpdate: "NO ACTION" }  )  @JoinColumn([{ name: "teacher_id", referencedColumnName: "id" }])  teacher: Teacher;}当我从该关联中检索一行时,我想要做的是获取教师和课堂详细信息。我是这样做的,import "reflect-metadata";import { createConnection, getRepository } from "typeorm";import { Teacherclassroom } from "./entity/Teacherclassroom";import { Classroom } from "./entity/Classroom";import { Teacher } from "./entity/Teacher";createConnection().then(async connection => {    const myRepository = getRepository(Teacherclassroom);    const test = myRepository.find({ relations: ["teacher", "classroom"] });    console.log(test);}).catch(error => console.log(error));我收到这个错误,Relation was not found, please check if it is correct and really exist in your entity.
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

只需更改class为classroom在课堂关系中


@ManyToOne(() => Classroom,classroom => classroom.teacherclassrooms,

{ onDelete: "NO ACTION", onUpdate: "NO ACTION" })

@JoinColumn([{ name: "class_id", referencedColumnName: "id" }])

classroom: Classroom;只需更改class为classroom在课堂关系中


@ManyToOne(() => Classroom,classroom => classroom.teacherclassrooms,

{ onDelete: "NO ACTION", onUpdate: "NO ACTION" })

@JoinColumn([{ name: "class_id", referencedColumnName: "id" }])

classroom: Classroom;


查看完整回答
反对 回复 2022-05-22
  • 1 回答
  • 0 关注
  • 304 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信