【发布时间】:2022-02-21 22:03:43
【问题描述】:
我需要有关 typeorm、typegraphql 的多对多问题的帮助。我尝试了很多方法将项目添加到 M-T-M 关系表中,但无法做到。我遵循了 TypeORM 文档,但我认为我遗漏了一些东西。
当我尝试从学院获取教师时,它返回未定义。应该是什么类型的?我认为它是一个数组,我可以轻松地将一个项目推送到它,或者传播旧值并添加一个项目。但是,上述方法都不起作用。
@ObjectType()
@Entity()
export class Faculty extends BaseEntity {
@Field(() => ID)
@PrimaryColumn()
id: string;
@Field(() => [Department])
@OneToMany(() => Department, (department) => department.faculty)
departments: Department[];
@Field(() => [Teacher], { nullable: true })
@ManyToMany(() => Teacher)
@JoinTable()
teachers: Teacher[];
@BeforeInsert()
setId() {
this.id = uuid();
}
}
@ObjectType()
@Entity()
export class Teacher extends BaseEntity {
@Field(() => ID)
@PrimaryColumn()
id: string;
@Field(() => [Faculty])
@ManyToMany(() => Faculty, (faculty) => faculty.teachers)
faculties: Faculty[];
@BeforeInsert()
setId() {
this.id = uuid();
}
}
@Mutation(() => Teacher)
async addTeacherToFaculty(
@Arg('teacherId') teacher_id: string,
@Arg('facultyId') faculty_id: string
): Promise<Teacher> {
const teacher = await Teacher.findOne({ where: { id: teacher_id } });
let faculty = await Faculty.findOne({ where: { id: faculty_id } });
if (!teacher) {
throw new Error('Invalid credentials, please provide correct teacher ID');
}
if (!faculty) {
throw new Error('Invalid credentials, please provide correct faculty ID');
}
const { teachers } = faculty;
if (teachers && teachers.length == 0) {
faculty.teachers = [teacher];
} else {
faculty.teachers?.push(teacher);
}
console.log(faculty.teachers);
await faculty.save();
return teacher;
}
【问题讨论】:
标签: typescript typeorm typegraphql