Node.JS Typescript TypeORM ManyToMany 与空结果集的关系

问题描述 投票:0回答:1

我有以下打字稿 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}"}
node.js typescript many-to-many typeorm node.js-typeorm
1个回答
0
投票

findOneOrFail
会抛出。需要捕获异常并将其作为不存在的实体进行处理。

© www.soinside.com 2019 - 2024. All rights reserved.