[英]OneToOne Join in Foalts and Typeorm
我有两个用 Foalts 框架编写的实体,它们正在使用 Typeorm。
这是user.entity.ts
:
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
password: string;
@Column({ unique: true })
phone: string
@OneToOne(() => UserProfile)
@JoinColumn()
userProfile: UserProfile
}
第二个是用户资料:
@Entity()
export class UserProfile extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstname: string;
@Column()
surname: string
@Column()
email: string
@Column()
birthDate: number
}
export { DatabaseSession } from '@foal/typeorm';
我的问题是:我如何在我的 controller 中编写一个查询,以便在 output 中有这样的 object:
{
"id":41,
"phone":"+18885555555",
"userProfile" : {
"id": 12,
"firstname": "Pourya",
"surname": "Daneshvar",
"email": "example@example.me",
"birthDate": 1613503707
}
}
这是我的 controller:
@Get('/user/profile')
async getUserProfile(ctx: Context) {
const user = await ...
...
return new HttpResponseOK(user)
}
最简单的方法是在关系中添加Eager: true
选项,如下所述:
@Entity()
export class User extends BaseEntity {
// ...
@OneToOne(() => UserProfile, { eager: true } )
@JoinColumn()
userProfile: UserProfile;
}
或者,如果您不希望每次加载用户时都检索 UserProfile 数据,您可以将关系选项添加到find
或findOne
,例如
const user = await User.findOne({ where: { id: userId } , relations: ["userProfile"] });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.