【问题标题】:OneToOne Join in Foalts and TypeormOneToOne 加入 Foalts 和 Typeorm
【发布时间】:2021-05-19 16:50:48
【问题描述】:

我有两个用 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';

我的问题是:如何在我的控制器中编写查询以在输出中有这样的对象:

{
    "id":41,
    "phone":"+18885555555",
    "userProfile" : {
      "id": 12,
      "firstname": "Pourya",
      "surname": "Daneshvar",
      "email": "example@example.me",
      "birthDate": 1613503707
    }
}

这是我的控制器:

@Get('/user/profile')
  async getUserProfile(ctx: Context) {
    const user = await ...
    ...
    return new HttpResponseOK(user)
  }

【问题讨论】:

    标签: typescript typeorm


    【解决方案1】:

    最简单的方法是在关系中添加Eager: true 选项,描述为here

    @Entity()
    export class User extends BaseEntity {
        // ...
        @OneToOne(() => UserProfile, { eager: true } )
        @JoinColumn()
        userProfile: UserProfile;
    }
    

    或者,如果您不希望每次加载用户时都检索 UserProfile 数据,您可以将 relations 选项添加到 findfindOne,例如

     const user = await User.findOne({ where: { id: userId } , relations: ["userProfile"] });
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2021-06-10
      • 1970-01-01
      • 2020-10-10
      • 2020-05-06
      • 2021-12-12
      • 1970-01-01
      • 2013-10-13
      • 2021-01-01
      相关资源
      最近更新 更多