TypeORM 关系:只有 ID 而不是整个实例

sto*_*nie 4 foreign-keys relationship typeorm

根据文档,在 TypeORM 中,关系定义如下:用户只有一个配置文件。

import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from "typeorm";
import {Profile} from "./Profile";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToOne(type => Profile)
    @JoinColumn()
    profile: Profile;

}
Run Code Online (Sandbox Code Playgroud)

问题

创建新用户时,为什么我必须传递实体的完整实例(profile: Profile)而不是 - 像往常一样 - 只有一个 ID?像这样:

@OneToOne(type => Profile)
    @JoinColumn()
    profileId: number;
Run Code Online (Sandbox Code Playgroud)

没有别的办法吗?

如果您必须对 4 个外键进行 4 次查询以获取相应的实例而不是 ID,则此过程会导致大量不必要的开销。

我将非常感谢帮助解决这个问题!

iY1*_*1NQ 6

在 TypeORM 中,导航字段(此处profile)可以与普通外键字段 ( profileId)结合使用。所以你可以写:

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToOne(type => Profile)
    @JoinColumn()
    profile: Profile;

    @Column()
    profileId: number;

}
Run Code Online (Sandbox Code Playgroud)

然后由您决定是更新与实体对象的关系还是仅更新配置文件 ID。

  • [此处](https://typeorm.io/#/relations-faq/how-to-use-relation-id-without-joining-relation)在稍微不同的上下文中提到了它。你的担心是对的,TypeORM 抽象/隐藏了很多东西,结果有时是不可预见的,但大多数情况下阅读源代码可以澄清一些事情。 (3认同)