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?
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
here there's an exmple
I wanna show lyrics from certain user and certain song so I use leftJoin because I need in the where
But in this example I don't wanna show the properties from user and song, what I wanna show is my lyrics and this