我有以下打字稿 TypeORM 模型:
@Entity()
export class Teacher extends EntityBase {
@Column({ length: 256 })
public firstName: string
@Column({ length: 256 })
public lastName: string
@Column({ unique: true, length: 256 })
public email: string
@ManyToMany((type) => Student, (student) => student.teachers, { nullable: true })
@JoinTable()
public students: Student[]
constructor(first: string, last: string, email: string) {
super();
this.firstName = first;
this.lastName = last;
this.email = email;
//this.students = []; TypeORM initialization failed! InitializedRelationError: Array initializations are not allowed in entity relations
}
}
以下查询:
public override async GetByEmail (email: string): Promise<Teacher | null> {
return await this._repository.findOneOrFail({
where: { email: email },
relations: ["students"]
});
}
失败:
Exception: {"criteria":{"where":{"email":"[email protected]"},"relations":["students"]},"message":"Could not find any entity of type \"Teacher\" matching: {\n \"where\": {\n \"email\": \"[email protected]\"\n },\n \"relations\": [\n \"students\"\n ]\n}"}
findOneOrFail
会抛出。需要捕获异常并将其作为不存在的实体进行处理。