TYPEORM joins and maps

353 Views Asked by At

I have been learning about typeorm and its join types and could not grasp how these join types work, these were used in a query builder function of a code I was going through and had a hard time understanding their significance and what they actually do. I have figured out a little by looking into the documentation of typeorm but without any concrete examples it is hard to fully understand their working and functioning.

leftJoin-basic Left join but does not take the other table values in the resultant table

leftJoinAndSelect- same as leftJoin but takes the values from both tables into the resultant table.

I might be wrong in my interpretations so please correct me if that is the case

But I had a hard time understanding this join- leftJoinAndMapOne

this is roughly how the code snippet looks like


return MyQueryBuilder
      .leftJoinAndSelect("table1.atr1", "atr1_alias")
      .leftJoinAndSelect("table1.atr2", "atr2_alias")
      .leftJoinAndSelect("table1.atr3", "atr3_alias")
      .leftJoinAndMapOne(
        //some conditions from other tables
      )
      .leftJoinAndSelect("table1.atr1", "atr1_alias")

If anyone can explain the same with an example it would be of great help as it does not

1

There are 1 best solutions below

0
Farzad.Jafari On

I hope that I can explain leftJoinAndMapOne to you:

Assume you have a user that has multiple photos one of them is for the profile photo.

class User {
  @OneToMany(() => Photo, (photo) => photo.owner, {
    cascade: true,
  })
  photos: Photo[];
}
class Photo {
  @Column({
    type: 'boolean',
    nullable: true,
    default: false,
  })
  isForProfile: boolean;

  @ManyToOne(() => User, (user) => user.photos)
  owner: User;

}

Now you can access the profile photo directly from the user without loading and searching in all user's photos.

Official sample of typeorm:

const user = await createQueryBuilder("user")
    .leftJoinAndMapOne(
        "user.profilePhoto", // new property that you will add to the user
        "user.photos", // relation field in user entity
        "photo", // related table or entity
        "photo.isForProfile = TRUE", // condition: you can add condition and parameters used in condition
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()

This will load Timber's profile photo and set it to user.profilePhoto.

I hope this explanation helps you.