fafa.mnzm
fafa.mnzm

Reputation: 611

have RelationID on both sides of OneToOne relation typeorm postgres

I have user and profile entities and they have a onetoone relation together. I am using typeorm and postgres I used joincolumn on user and have access to RelationId (or Column) profileId on user side However I want to have userId on profile side as well How can I accomplish this?

something like this:

export class User extends BaseEntity {

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

@Column()
profileId:number

}

////////

export class Profile extends BaseEntity{

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

@Column()
userId: number

}

Upvotes: 3

Views: 2881

Answers (1)

Ivan Slavinskyi
Ivan Slavinskyi

Reputation: 41

You may find answer in documantation.

Relations can be uni-directional and bi-directional. Uni-directional are relations with a relation decorator only on one side. Bi-directional are relations with decorators on both sides of a relation.

@JoinColumn must only be on one side of the relation - on the table that will own the foreign key.

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;

}

Upvotes: 4

Related Questions