i have a doubt with Typeorm getMany() function. I have this code
const res = await this.repo
.createQueryBuilder('result')
.leftJoinAndSelect(
UserAnag,
'useranag',
'useranag.playerId = result.playerId',
)
.where('result.server = :idServer', { idServer: serverId })
.andWhere('result.raceId = :idRace', { idRace: raceId })
.getMany();
This code return only the result entity, not the useranag entity. If i change with getRawMany() returns all the data i need, but in raw format not entity object like.
It return as getRawMany() function expect
result.id,
result.position,
useranag.id,
useranag.name
etc
instead i expected with getMany() function
result.id,
result.position,
useranag: {
id: xx,
name: yyy
}
I can manually recreate the object but i want understand wher's the problem. My useranag and result entity have a join field playerId but ther's no relation mapped in entity.
On Typeorm manual demonstrate that i can user leftjoinAndSelect also for non related entity and with getMany() function
These are my Entity that i join
@Entity()
export class Results {
@PrimaryGeneratedColumn()
id: number;
@Column()
position: number;
@Column()
laps: number;
@Column({ type: 'time', precision: 3 })
bestLaps: Date;
@Column({ type: 'time', precision: 3 })
gap: Date;
@Column()
penalties: number;
@Column()
server: number;
@Column()
playerId: string;
@ManyToOne(() => Cars, (cars) => cars.result)
car: Cars;
@ManyToOne(
() => Competitionraces,
(competitionRaces) => competitionRaces.result,
)
race: Competitionraces;
}
and these are the other entity to join with , useranag
@Entity()
export class UserAnag {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
surname: string;
@Column()
psn: string;
@Column()
discord: string;
@Column()
drivernumber: number;
@Column()
playerId: number;
@OneToOne(() => User, (user) => user.useranag, {
onDelete: 'CASCADE',
})
@JoinColumn()
user: User;
@ManyToOne(() => Discord, (useranag) => useranag.siglaTeam)
discordTeam: Discord;
}
I solve the problem and i will show the best solution i can find for this problem:
On my Entity i create this field
@ManyToOne(() => UserAnag, (useranag) => useranag.results, {
createForeignKeyConstraints: false,
})
@JoinColumn({ name: 'playerId', referencedColumnName: 'playerId' })
useranag: UserAnag;
with createForeignKeyConstraints: false this does not create the foreign key column on my database but create the join relation.
Then on my query, instead of querybuilder, i use classic find()
return await this.repo.find({
relations: { car: true, useranag: true },
});