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

TypeORM relationship: Only IDs instead of whole instances

根据documentation,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;

}

问题

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

@OneToOne(type => Profile)
    @JoinColumn()
    profileId: number;

难道没有别的办法吗?

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

如果能帮助我解决这个问题,我将不胜感激!

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

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

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

    @Column()
    profileId: number;

}

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