I faced this issue when I get data from over 3 joined tables via TypeORM in Nest.js. Here are 3 entities:
export class TableA {
@PrimaryGeneratedColumn()
@Index({ unique: true })
@ApiProperty()
tableAId: number;
@OneToMany((type) => TableB, (tableB) => tableB.tableA, { nullable: true })
@ApiProperty({ type: 'object', description: 'TableB[]' })
tableBs: TableB[];
static findWithMinimalRelations(tableCId: string): SelectQueryBuilder<TableA> {
return (
this.createQueryBuilder('tableA')
.leftJoinAndSelect('tableA.tableBs', 'tableB', '"tableB"."tableCId" = :tableCId', {tableCId})
);
}
}
export class TableB {
@PrimaryGeneratedColumn()
@Index({ unique: true })
@ApiProperty()
tableBId: number;
@Column('enum', { enum: Option, default: Option.default })
@ApiProperty({ enum: Option, default: Option.default })
option: Option;
@ManyToOne((type) => TableC, (tableC) => tableC.tableBs)
@Index({ unique: true })
@JoinColumn({ name: 'tableCId', referencedColumnName: 'tableCId' })
@ApiProperty({ description: 'TableC', type: 'object' })
tableC: TableC;
@ManyToOne((type) => TableA, (tableA) => tableA.tableBs)
@Index({ unique: true })
@JoinColumn({ name: 'tableAId', referencedColumnName: 'tableAId' })
@ApiProperty({ description: 'TableA', type: 'object' })
tableA: TableA;
}
export class TableC {
@PrimaryGeneratedColumn()
@Index({ unique: true })
@ApiProperty()
tableCId: number;
@OneToMany((type) => TableC, (tableB) => tableB.tableC, { nullable: true })
@ApiProperty({ type: 'object', description: 'TableC[]' })
tableBs: TableC[];
}
When I call findWithMinimalRelations of TableA method, it generates below query.
SELECT
"tableA"."tableAId" AS "tableA_tableAId"
"tableB"."tableBId" AS "tableB_tableBId",
"tableB"."option" AS "tableB_option",
"tableB"."tableC" AS "tableB_tableC",
"tableB"."tableAId" AS "tableB_tableAId"
FROM
"tableA" "tableA"
LEFT JOIN "account_tableA" "tableB" ON "tableB"."tableAId" = "tableA"."tableAId"
AND (
"tableB"."tableAId" = "tableA"."tableAId"
AND "tableB"."tableC" = $1
)
If I run this query, I can find the result matched with condition.
But the result of findWithMinimalRelations has empty tableBs.
When I call findWithMinimalRelations function, I want to get the result has tableBs.