Multiple JOIN with TYPEORM

Reyhan Fikran Dzikriansyah picture Reyhan Fikran Dzikriansyah · Mar 5, 2019 · Viewed 13.2k times · Source

I'm new on typeorm, maybe someone can resolve my problem.
I have some query like :

SELECT t1.id,t2.id_2,t3.event,t3.column1,t4.column1 FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id
INNER JOIN table3 t3 ON t2.event = t3.event
INNER JOIN table4 t4 ON t4.id = t2.id_2 WHERE t3.event = 2019

How to convert this query to typeorm?

Answer

Mukyuu picture Mukyuu · Mar 6, 2019

Let's break them one by one, shall we? Assuming you know how then it would be simple:

await getManager()
        .createQueryBuilder(table1, 't1')
        .addSelect('t1.id', 't1_id')
        .addSelect('t2.id_2', 't2_id_2')
        .addSelect('t3.event', 't3_event')
        .addSelect('t4.column1', 't4_column1') // up to this point: SELECT t1.id,t2.id_2,t3.event,t3.column1,t4.column1 FROM table1 t1
        .innerJoin(table2, 't2', 't1.id = t2.id') //INNER JOIN table2 t2 ON t1.id = t2.id
        .innerJoin(table3, 't3', 't2.event = t3.event') // INNER JOIN table3 t3 ON t2.event = t3.event
        .innerJoin(table4, 't4', 't4.id = t2.id_2') // INNER JOIN table4 t4 ON t4.id = t2.id_2 
        .where('t3.event = 2019') // WHERE t3.event = 2019
        .getRawMany() // depend on what you need really

You can refer to this to check what output would you like: https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-values-using-querybuilder

Whether you want the data as entities (getOne and getMany) or what it is(getRawOne and getRawMany)