初始化前无法访问“用户” - NestJs 和 typeORM

问题描述 投票:0回答:2

尝试创建双向 OneToOne 关系时出现以下错误。我基本上遵循了 typeORM 文档,所以不确定为什么会收到错误。

ReferenceError:初始化前无法访问“用户”

下面的用户类别

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
}

下面的用户个人资料类别

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;
}
nestjs typeorm
2个回答
0
投票

也许试试这个:

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

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

0
投票

我想这个方法可以帮助你。您应该在关系属性中使用关系包装类型以避免循环依赖问题。您可以参考此链接:https://typeorm.io/#relations-in-esm-projects

代码示例:

import { Column, PrimaryGeneratedColumn, OneToMany, Entity, Relation } from 'typeorm';
import { Address } from './address.entity';

@Entity({ name: 'profile' })
export class Profile {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 255, nullable: true })
  avatar: string;

  @Column({ type: 'int' })
  user_id: number;

  @Column({ type: 'varchar', length: 255, nullable: true })
  cover: string;

  @Column({ type: 'text', nullable: true })
  biography: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  instagram: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  facebook: string;

  @OneToMany(() => Address, (address) => address.profile)
  address: Relation<Address>[];
}
© www.soinside.com 2019 - 2024. All rights reserved.