TypeORM 关系:只有 ID 而不是整个实例 [英] TypeORM relationship: Only IDs instead of whole instances

查看:55
本文介绍了TypeORM 关系:只有 ID 而不是整个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to the documentation, in TypeORM a relationship is defined as follows: A user has exactly one profile.

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;

}

问题

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

When creating a new user, why do I have to pass a complete instance of the entity (profile: Profile) instead of - as usual - only one ID? Like this:

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

没有别的办法吗?

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

This procedure causes a large, unnecessary overhead, if you have to make 4 queries for 4 foreign keys to get the corresponding instance instead of the ID.

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

I would be very grateful for help to get around this!

推荐答案

在 TypeORM 中,导航字段(此处为 profile)可以与普通外键字段(profileId>).所以你可以写:

In TypeORM the navigation field (here profile) can be combined with the plain foreign key field (profileId). So you can write:

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

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

    @Column()
    profileId: number;

}

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

Then it's up to you if you update the relation with the entity object or only with the profile id.

这篇关于TypeORM 关系:只有 ID 而不是整个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆