Search code examples
typeorm

TypeORM, Query entity based on relation property


I would like to query an entity based on a related property, for instance:

const x = await repo.findOne({ name: 'foo', parent: { name: 'foo' }});

but it aways returns a null when I query by its related parent

I alread added : relations: ['parent'], already set relation as {eager:true}

When I Query by parent: {id: X} it works. but I must query by its name.

What should I do to get this query working in TypeORM

It would be similar to:

select * from entity inner join parent ... where entity.name = 'foo' and parent.name = 'foo'


Solution

  • find/findOne doesn't allow filtering by nested relation properties. Go for QueryBuilder instead with something like

    const x = await repo.createQueryBuilder("foo")
        .innerJoinAndSelect("foo.parent", "parent")
        .where("parent.name = :name", { name })
        .getOne()
    

    Check here for a similar question.

    Edit: querying by relations is now supported in typeorm >= 0.3. See the release notes for details.