0
votes

I am getting the following error when trying to create a bidirectional OneToOne relationship. I essentially followed typeORM docs so not sure why I get the error.

ReferenceError: Cannot access 'User' before initialization

User Class below

import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { UserProfile } from "./userProfile.entity"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    password: string;

    @Column()
    email: string;

    @Column()
    timezone: string;

    @OneToOne(type => UserProfile, userProfile => userProfile.id)
    userProfile: UserProfile
}

User profile class below

import { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from "typeorm"
import { User } from './user.entity'
import { Media } from './media.entity'

@Entity()
export class UserProfile {
    @PrimaryGeneratedColumn()
    id: number

    @OneToOne(type => User, user => user.userProfile)
    @JoinColumn()
    user: User;

    @OneToOne(type => Media, {
        cascade: true
    })
    @JoinColumn()
    avatar: Media;

    @Column()
    avatarId: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @Column()
    age: number;
}
1
Possible duplicate: stackoverflow.com/questions/60363353/… For me adding all entities into one Barrel and changing all imports to that barrel solved the issue. e.g.: import { User, Media } from './entities';west efan

1 Answers

0
votes

Maybe try this :

// User
@OneToOne(type => UserProfile, userProfile => userProfile.user)
userProfile: UserProfile

// UserProfile
@OneToOne(type => User, user => user.userProfile)
@JoinColumn()
user: User;