【问题标题】:have RelationID on both sides of OneToOne relation typeorm postgres在 OneToOne 关系 typeorm postgres 的两边都有 RelationID
【发布时间】:2023-03-28 04:40:01
【问题描述】:

我有用户和个人资料实体,它们之间存在一对一的关系。 我正在使用 typeorm 和 postgres 我在用户上使用了 joincolumn 并且可以在用户端访问 RelationId(或 Column)profileId 但是我也想在个人资料方面有 userId 我怎样才能做到这一点?

类似这样的:

export class User extends BaseEntity {

@OneToOne(()=>Profile)
profile:number

@Column()
profileId:number

}

////////

export class Profile extends BaseEntity{

@OneToOne(()=>Profile)
user: number

@Column()
userId: number

}

【问题讨论】:

    标签: postgresql typeorm one-to-one


    【解决方案1】:

    您可以在文档中找到答案。

    关系可以是单向和双向的。单向是仅在一侧与关系装饰器的关系。双向是关系两侧的装饰器关系。

    @JoinColumn 只能在关系的一侧 - 在将拥有外键的表上。

    import {User} from "./User";
    
    @Entity()
    export class Profile {
    
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        gender: string;
    
        @Column()
        photo: string;
    
        @OneToOne(type => User, user => user.profile) // specify inverse side as a second parameter
        user: User;
    
    }
    
    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, profile => profile.user) // specify inverse side as a second parameter
        @JoinColumn()
        profile: Profile;
    
    }
    

    【讨论】:

    • 感谢您的评论。在一对一关系中,关系 ID 仅存储在包含 joinColumn 的表中。我想在两边都有每个的realtionId。在当前情况下,我只会在用户实体上拥有 profileId。我还想在个人资料实体上拥有 userId。我正在使用 graphql,我需要查询用户,而不必先查询配置文件。
    • 您可以使用类似 this.profileRepository.findOne({ where: { profileId: 1}, relations: ['user']}) 的东西,然后描述 graphQlL ObjectType DTO 将是配置文件和用户的位置。或者您应该阅读文档 doug-martin.github.io/nestjs-query 并使用 Relation/FiltarebleRelation 装饰器
    • 谢谢,这似乎是一个不错的选择。我会试一试的。
    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 2021-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多