实体之间的循环依赖

时间:2021-01-19 13:21:41

标签: node.js postgresql nestjs typeorm

我有三个实体 TestUser 、 TestProfile 和 TestPhoto ,其中 TestUser 与 TestProfile 有一对一关系,TestProfiles 与 TestPhoto 有一对一关系,最后 TestPhoto 与可能尚未创建的 User 有这种多对一关系

我在定义我的实体时使用级联,我希望在我的 UserService 中通过一次调用创建它们,但面临这种循环依赖:“TestPhoto”错误并且从那时起没有任何进展,我认为它可能不是什么应该在现实生活场景中做,但除此之外,任何可能的黑客攻击还是根本不可能?

@Entity()
@Unique(["name"])
export class TestUser {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToOne(() => TestProfile,{
        cascade:true,
        nullable:true
    })
    @JoinColumn()
    profile: TestProfile;
    @Column({nullable:true})
    profileId: number

    @OneToMany(() => TestPhoto, photo => photo.user)
    photos: TestPhoto[];

}


@Entity()
export class TestProfile {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    gender: string;

    @OneToOne(type=>TestPhoto,{
        cascade:true,
        nullable:true
    })
    @JoinColumn()
    photo: TestPhoto;

    @Column({nullable:true})
    photoId: number

}

@Entity()
export class TestPhoto {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    url: string;

    @ManyToOne(() => TestUser, user => user.photos,{
        cascade:true,
        nullable:true
    })
    user: TestUser;
    @Column({nullable:true})
    userId: number; 

}

并在我的 UserService 中将调用抽象为如下

const user = new TestUser(); 
const profile1 = new TestProfile(); 
const photo1 = new TestPhoto(); 
photo1.user = user;
profile1.photo  = photo1; 
user.profile = profile1

await connection.manager.save(user);  

2 个答案:

答案 0 :(得分:1)

在写代码之前,请随意理解循环依赖的概念; jsonplaceholder。在您的情况下可能存在循环依赖,但在现实生活中可能不会。您需要做的是让您的实体/模态成为双方的 forwardRef。然后在另一个服务的构造函数中使用 @Inject(forwardRef(() => YourService)) 使服务可以注入其他服务。如果您不明白,我将发布一个完整的示例,说明循环依赖在您的案例和现实生活场景中是如何工作的。

答案 1 :(得分:0)

这些实体是否存在于同一个文件中?

我使用 import type TS 的特性来解决模块解析级别的循环依赖。我不确定你的情况是否如此。