Get a Quote Right Now

Edit Template

Inner Join in Typeorm

 Inner and left joins

If you want to use INNER JOIN instead of LEFT JOIN just use innerJoinAndSelect instead:

const user = await createQueryBuilder("user")
    .innerJoinAndSelect(
        "user.photos",
        "photo",
        "photo.isRemoved = :isRemoved",
        { isRemoved: false },
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()

This will generate:

SELECT user.*, photo.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
    WHERE user.name = 'Timber'

The difference between LEFT JOIN and INNER JOIN is that INNER JOIN won’t return a user if it does not have any photos. LEFT JOIN will return you the user even if it doesn’t have photos.

Join without selection

You can join data without its selection. To do that, use leftJoin or innerJoin:

const user = await createQueryBuilder("user")
    .innerJoin("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()

This will generate:

SELECT user.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id
    WHERE user.name = 'Timber'

This will select Timber if he has photos, but won’t return his photos.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *