在 TypeOrm 中,OneToMany 和 ManyToOne 的默认获取类型是什么?

mom*_*omo 2 typeorm

Typeorm的官方文档规定,如果使用Lazy,则必须使用promise。如果不承诺,默认的获取类型会是急切加载吗?但是,我检查了一下,它似乎正在加载 Lazy,而不是 Eager。JPA默认的音高类型如下:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
Run Code Online (Sandbox Code Playgroud)

TypeOrm 的默认获取类型是否相同?

Era*_*han 7

TLDR:既不是lazy也不是eager


如果您检查Typeorm 关系选项代码

export interface RelationOptions {
    ...

    /**
     * Set this relation to be lazy. Note: lazy relations are promises. When you call them they return promise
     * which resolve relation result then. If your property's type is Promise then this relation is set to lazy automatically.
     */
    lazy?: boolean;
    /**
     * Set this relation to be eager.
     * Eager relations are always loaded automatically when relation's owner entity is loaded using find* methods.
     * Only using QueryBuilder prevents loading eager relations.
     * Eager flag cannot be set from both sides of relation - you can eager load only one side of the relationship.
     */
    eager?: boolean;

    ...
}

Run Code Online (Sandbox Code Playgroud)

您可以看到,Typeorm 默认情况下不会加载任何类型的关系。基本上,它既不是lazy也不是eager

如果您既不设置lazy也不设置eager,它根本不会加载关系,除非您在find选项或中指定它QueryBuilder

请参阅Typeorm 文档中的以下示例find

const user = userRepository.find({
    where: {
        name: "John",
    },
    relations: ["project"],
});

// Think user has a one-to-many relationship with projects, then:
// const projects = user.projects;
Run Code Online (Sandbox Code Playgroud)

如果指定了lazyeager则不需要在find选项中指定。但使用时仍然需要指定连接条件QueryBuilder

为了lazy

const user = userRepository.find({
    where: {
        name: "John",
    }
});

// Need await for `lazy`:
// const projects = await user.projects;
Run Code Online (Sandbox Code Playgroud)

为了eager

const user = userRepository.find({
    where: {
        name: "John",
    }
});

// No await for `eager`:
// const projects = user.projects;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。干杯!