首页 > 解决方案 > 在 TypeOrm 中,OneToMany 和 ManyToOne 的默认获取类型是什么?

问题描述

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

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

TypeOrm 的默认 fetch 类型是否相同?

标签: typeorm

解决方案


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;

    ...
}

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

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

See the below example from Typeorm Documentation for 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;

If you specify lazy or eager then you don't need to specify it in find options. But you will still have to specify the join condition when using QueryBuilder.

For lazy:

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

// Need await for `lazy`:
// const projects = await user.projects;

For eager:

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

// No await for `eager`:
// const projects = user.projects;

Hope this helps. Cheers !!!


推荐阅读