Difference between leftJoin and leftJoinAndSelect in TypeORM

44 Views Asked by At

I have the following query using TypeORM on a NestJS backend with PostgreSQL:

const queryBuilder = this.usersRepository
      .createQueryBuilder('user')
      .select([
        'user.id',
        'userWallets.balance',
        'userWallets.currency',
      ])
      .leftJoin('user.userWallets', 'userWallets')

In user entity the one to many relationship with UserWallet is defined.

 @OneToMany(() => UserWallet, (userWallet) => userWallet.user)
  userWallets: UserWallet[];

And the many to one with User in user wallet entity

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

There are two wallets per user, so when I write the query as above I'm getting the expected array of userWallets but it only always has one element. If I write the query with a leftJoinAndSelect then I get the expected two elements in the userWallets array.

const queryBuilder = this.usersRepository
      .createQueryBuilder('user')
      .select([
        'user.id',
      ])
      .leftJoinAndSelect('user.userWallets', 'userWallets')

I thought that by including the user wallets field in the main select I would get them all, but there seems to be a difference and I cannot find any clarification in the TypeORM docs or elsewhere. What is the difference?

1

There are 1 best solutions below

0
Arellano Lahio On

Maybe you need to add .getMany(), the different is if you need show properties from userWallets you have to use leftJoinAndSelect, but if you only need userWallets for example on a .where() but u doesn't need show properties from userWallets only use this entity on the .where() you could use leftJoin

const queryBuilder = this.usersRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.userWallets', 'userWallets')
      .select([
        'user.id',
      ])
      .getMany()

here there's an exmple

return await repository.createQueryBuilder('letra')
    .leftJoinAndSelect('letra.Comentarios', 'comentarios')
    .leftJoinAndSelect('letra.Configuraciones', 'configuraciones')
    .leftJoin('letra.Usuario', 'usuario')
    .leftJoin('letra.Cancion', 'cancion')
    .where('usuario.UsuarioId = :usuarioId AND cancion.CancionId = :cancionId', {
        usuarioId, 
        cancionId
    })
    .getManyAndCount()

I wanna show lyrics from certain user and certain song so I use leftJoin because I need in the where

.where('usuario.UsuarioId = :usuarioId AND cancion.CancionId = :cancionId', {
        usuarioId, 
        cancionId
    })

But in this example I don't wanna show the properties from user and song, what I wanna show is my lyrics and this

.leftJoinAndSelect('letra.Comentarios', 'comentarios')
.leftJoinAndSelect('letra.Configuraciones', 'configuraciones')