Search code examples
typescripttypeormfoalts

OneToOne Join in Foalts and Typeorm


I have two entities that written in Foalts framework and they are using Typeorm.

This is 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

}

And second one is user profile:

@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';

My question is: How can i write a query in my controller to have an object like this in output:

{
    "id":41,
    "phone":"+18885555555",
    "userProfile" : {
      "id": 12,
      "firstname": "Pourya",
      "surname": "Daneshvar",
      "email": "[email protected]",
      "birthDate": 1613503707
    }
}

This is my controller:

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

Solution

  • The easiest way is to add Eager: true option to the relation, described here:

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

    Alternatively, if you don't want UserProfile data to be retrieved every time you load User, you can add relations option to find or findOne, e.g.

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