Search code examples
typeormnest

Make JOINED query with OR in Where clause in Typeorm With Repository method


Im trying to build this query in TYPEORM using connection.getRepository method in Nestjs.

                SELECT
                    "car"."RowID"
                FROM
                    "cars"."car" "car"
                    LEFT JOIN "cars"."doors" "doors" ON "car"."doorID" = "doors"."doorID"
                    LEFT JOIN "cars"."wheels" "wheels" ON "car"."wheelID" = "wheels"."wheelID"
                    LEFT JOIN "cars"."engines" "engines" ON "car"."engineID" = 
                    "engines"."engineID"
                WHERE
                        ("car"."Status" = 0 OR "car"."Status" = 2) AND
                        "car"."RetryAttempts" < 5 AND
                        ("doors"."Status" = 3 OR "doors"."Status" = 4) AND
                        ("wheels"."Status" = 3 OR "wheels"."Status" = 4) AND
                        ("engines"."Status" = 3 OR "engines"."Status" = 4)
            )``
    ````
    This is what i came up with but it doesnt work.

this.connection
            .getRepository(CarsEntity)
            .find({
                select: ["rowID"],
                join: {
                    alias: "car",
                    leftJoinAndSelect: {
                        engines: "car.engines",
                        doors: "car.doors",
                        wheels: "car.wheels",
                    },
                },
                where: {
                    retryAttempts: LessThan(5),
                    status:In([
                        0,2]
                    ),
                    engines: {
                        status: In([3,4]
                        )
                    },
                    doors: {
                        status: In([3,4]
                        )
                    },
                    wheels: {
                        status: In([3,4]
                        )
                    }
                }
            });

The where clause for this query looks like this

WHERE
    "CarsEntity"."retryAttempts" < @0
    AND "CarsEntity"."status" IN (@1, @2)
    AND "CarsEntity"."engineID" = @3
    AND "CarsEntity"."doorID" = @4
    AND "CarsEntity"."wheelID" = @5

Question is from where are are the extra fields comming from. Is it my query or should i search the entities? And what happens to my conditions for the status?


Solution

  • Make sure to have a version equal or greater than "typeorm": "^0.2.37",

    there was a bug that is fixed in this version. Previously i was using "typeorm": "^0.2.34