【问题标题】:How to expose foreign key column in the entity in TypeORM如何在 TypeORM 中的实体中公开外键列
【发布时间】:2020-12-16 04:46:17
【问题描述】:

我未能公开实体中的外键列,我觉得不能这样做很奇怪。

如果我不急于加载关系,至少我应该能够看到imageId 以了解关系存在的一些线索。所以当我做userRepository.findOne({email: emailaddress}) 时,即使我知道我不能以这种方式eager load 图像。但至少我可以看到imageId

@Column('datetime', { nullable: true, name: 'last_login' })
lastLogin: string;

@OneToOne(() => UserSetting)
@JoinColumn({ name: 'setting_id' })
setting: UserSetting;

@OneToOne(() => UserImage, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'image_id' })
image: UserImage;

imageUrl: { preview: string, thumbnail: string };

@OneToMany(() => Contact, contact => contact.user)
contacts: Contact[];

@OneToMany(() => Notification, notification => notification.user)
notifications: Notification[];

如您所见,没有定义imageId。我试着这样说。数据库无法同步,它也清除了我所有的图像数据。

@Column({name: 'image_id' })
imageId: string;

@OneToOne(() => UserImage, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'image_id' })
image: UserImage;

我在这里遗漏了一些简单的东西吗?

【问题讨论】:

    标签: typeorm


    【解决方案1】:

    您的User Entity 应如下所示:

    @Column({ nullable: true })
    imageId: string;
    
    @OneToOne(() => UserImage, userImage=> userImage.user, { onDelete: 'SET NULL' })
    @JoinColumn({ name: 'image_id' })
    image: UserImage;
    

    在你的UserImage Entity:

    @OneToOne(() => User, user=> user.image)
    user: User;
    

    【讨论】:

    • 试过了。它破坏了数据库。 imageId 也应该加上 {name: 'image_id'} 对吧?
    • 你是对的。我错过了 nullable: true 部分。但是添加之后,图片id数据就没了。
    • 也许你也应该设置默认值。
    • 为了记录,这是在创建实体时。不是为了修改它。如果您仍然在自动迁移模式下运行,添加外键列将清除整个外键列数据。
    猜你喜欢
    • 2021-02-03
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多