如何在TypeORM中公开实体中的外键列 [英] How to expose foreign key column in the entity in TypeORM
问题描述
我未能公开实体中的外键列,我感到很奇怪无法公开.
I have failed to expose the foreign key column in the entity which I feel weird to not be able to.
如果我不急于加载关系,至少我应该能够看到 imageId
以了解关系的存在.因此,当我执行 userRepository.findOne({email: emailaddress})
时,即使我知道我无法以这种方式 eager load
图像.但至少我可以看到 imageId
.
If I am not eager loading the relation, at least I should be able to to see the imageId
to have some clue of the existence of the relation. so when I do a userRepository.findOne({email: emailaddress})
, even I know that I can not eager load
the image this way. But at least I could see the 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
.我试着这样说.数据库无法同步,它也清除了我所有的图像数据.
As you can see, there is no imageId
defined. I tried to put it like this. The database just cannot be synced up and it wiped out all my image data too.
@Column({name: 'image_id' })
imageId: string;
@OneToOne(() => UserImage, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'image_id' })
image: UserImage;
我在这里遗漏了一些简单的东西吗?
Am I missing something simple here?
推荐答案
你的 User Entity
应该是这样的:
Your User Entity
should look like this:
@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;
这篇关于如何在TypeORM中公开实体中的外键列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!