Eager loading relational data without including link table data using KnexJS or TypeORM
0
votes
0
answers
49
views
I have **Table A** and **Table B** in my Postgres DB. The relations are built using link tables.
**Example**: ***ab_link*** table record contains ***a_id*** and ***b_id***.
What I am trying to do is get the ObjectA from table A with related ObjectB nested inside ObjectA.
When I am querying the data the ab_link table data is also added.
I have seen examples where we manually process the data after querying and I am trying to avoid that because my data relations are complex and nested multi-levels.
How can we get the A and B data without the ab_link recorded added to the queried data using **KnexJS**/**TypeORM**?
// USING KNEXJS
const a = await this.db('a')
.innerJoin('ab_links', 'a.id', 'ab_links.a_id')
.innerJoin('b', 'ab_links.b_id', 'b.id')
.where('a.id', id)
.then((rows) => {
return rows
})
.catch((error) => {
console.error(error);
});
Output a: {
id: 2,
name: 'Test',
b_id: 2
}
// USING TYPEORM
const req = await (await this.aRepository.queryBuilder(
a
))
.leftJoinAndSelect('a.ab_links', 'abl')
.leftJoinAndSelect('abl.b', 'b')
.where({ id: id })
.getOne();
Output: {
id:1,
name: 'test',
ab_links: {
id:4,
a_id:1,
b_id:2,
b: {
id:2,
name: 'test2'
}
}
}
Asked by JeffinJ
(101 rep)
Nov 2, 2023, 01:31 PM
Last activity: Nov 2, 2023, 02:13 PM
Last activity: Nov 2, 2023, 02:13 PM