Skip to content

Finding entity with with relation condition #4396

Closed

Description

@pxr64

Issue type:

[ X] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ X] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[X ] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Hello,

Is it possible to query an entity by placing a condition on one of its join columns?

For example, let's say I have the user entity that is in relation to the photos entity. (one-to-many relationship)

Why can't I use the following find configuration to filter the photos based an owning user's property. ?

Eg. I want all the photos for the users that have the firstName='Dan'

let photos = await photosRepo.find({
  where: {
      user: {
          firstName: 'Dan'
      }
  }
})

Activity

  1. Kononnable commented on Aug 31, 2019

    @Kononnable
    Contributor

    I guess you're looking for relations in find options parameters.

  2. anthonyjlmorel commented on Sep 10, 2019

    @anthonyjlmorel

    Hi guys, what's the status on this ?

    I would like to be able to request entities placing where condition on joined relations too which seems either missing or undocumented.

    Could you advise on this ?

  3. march08 commented on Sep 26, 2019

    @march08

    Same issue here. Anyone knows how to perform such a find?

    To give a better example

    Car { id, user }
    User { id, company }
    Company { id }
    
    // I want to find cars with specific company ID
    // something like this, but it's not working
    
    let carsOfCompany = await getRepository(Car).find({
     relations: ['user'],
     where: {
         user: {
             companyId: 'someid'
         }
     }
    })
    
  4. JunquerGJ commented on Oct 29, 2019

    @JunquerGJ

    @march08
    I cannot check it right now, but maybe this works for you:

    let carsOfCompany = await getRepository(Car).find({ join: { alias: "car", leftJoinAndSelect: { company: "car.company" } }, where : { company : { id : 'someid'}} })

  5. ilovett commented on Dec 4, 2019

    @ilovett

    The relation where only seems to work on id or perhaps primary columns,

    EG if your Car has user with JoinColumn() you could successfully query on where: { user: { id: 123 } } however it doesnt seem to work for non primary columns or joins such as the user's companyId

  6. ilovett commented on Dec 4, 2019

    @ilovett

    I found it unexpected that the orm was not able to consider that relational query

  7. ilovett commented on Dec 4, 2019

    @ilovett

    In my query I tried to find where { user: { mongoId: "xxx" } } but my Thing.find({ where: { user: { mongoId: "xxx" } }) yielded:

    WHERE "Thing"."user_id" = $1 -- PARAMETERS: [null]
    

    I am guessing because my Thing.user @JoinColumn is id and not mongoId

  8. alpharder commented on Dec 16, 2019

    @alpharder
    Contributor

    There's a workaround for filtering based on relation fields for findOne()/find() methods that I've discovered recently. The problem with filtering related table fields only exists for ObjectLiteral-style where, while string conditions work perfectly.

    Assume that we have two entities – User and Role, user belongs to one role, role has many users:

    @Entity()
    export class User {
      name: string;
    
      @ManyToOne(() => Role, role => role.users)
      role: Role;
    }
    
    @Entity()
    export class Role {
      @OneToMany(() => User, user => user.role)
      users: User[];
    }

    Now we can call findOne()/find() methods of EntityManager or repository:

    roleRepository.find({
      join: { alias: 'roles', innerJoin: { users: 'roles.users' } },
      where: qb => {
        qb.where({ // Filter Role fields
          a: 1,
          b: 2
        }).andWhere('users.name = :userName', { userName: 'John Doe' }); // Filter related field
      }
    });

    You can omit the join part if you've marked your relation as an eager one.

  9. darylcecile commented on Mar 22, 2020

    @darylcecile

    The relation where only seems to work on id or perhaps primary columns,

    EG if your Car has user with JoinColumn() you could successfully query on where: { user: { id: 123 } } however it doesnt seem to work for non primary columns or joins such as the user's companyId

    Honestly, this should stated in docs somewhere - saved me hours!

    Thank you

  10. kop7 commented on Apr 16, 2020

    @kop7

    find cars where model location is 2

    Car {id, name, model(ManyToOne->model)}
    Model{id, name, location(MaynToOne->location), cars(OneToMany->cars)}
    Location{id, name, models(OneToMany->models)}
    
    carRepository.find({
                relations: ['model','model.location'],
                where: {
                    'model.location': { id: 2},
                },
            });
    SELECT
           `Car`.`id` AS `Car_id`,
           `Car`.`title` AS `Car_title`,
           `Car`.`modelId` AS `Car_modelId`,
           `Car__model`.`id` AS `Car__model_id`,
           `Car__model`.`name` AS `Car__model_name`,
           `Car__model`.`locationId` AS `Car__model_locationId`,
           `Car__model__location`.`id` AS `Car__model__location_id`
        FROM `job` `Car` LEFT JOIN `model` `Car__model` ON `Car__model`.`id`=`Car`.`modelId`
        LEFT JOIN `location` `Car__model__location` ON `Car__model__location`.`id`=`Car__model`.`locationId`

    but miss locationId parameter?...
    what am I doing wrong?

  11. fchu commented on Apr 24, 2020

    @fchu

    I found the same issue, but for postgres...
    Seems like the find method signatures could be more strict, so that all the different variants don't get mingled without clear error handling

  12. david-macharia commented on May 6, 2020

    @david-macharia

    @COP

    find cars where model location is 2

    Car {id, name, model(ManyToOne->model)}
    Model{id, name, location(MaynToOne->location), cars(OneToMany->cars)}
    Location{id, name, models(OneToMany->models)}
    
    carRepository.find({
                relations: ['model','model.location'],
                where: {
                    'model.location': { id: 2},
                },
            });
    SELECT
           `Car`.`id` AS `Car_id`,
           `Car`.`title` AS `Car_title`,
           `Car`.`modelId` AS `Car_modelId`,
           `Car__model`.`id` AS `Car__model_id`,
           `Car__model`.`name` AS `Car__model_name`,
           `Car__model`.`locationId` AS `Car__model_locationId`,
           `Car__model__location`.`id` AS `Car__model__location_id`
        FROM `job` `Car` LEFT JOIN `model` `Car__model` ON `Car__model`.`id`=`Car`.`modelId`
        LEFT JOIN `location` `Car__model__location` ON `Car__model__location`.`id`=`Car__model`.`locationId`

    but miss locationId parameter?...
    what am I doing wrong?

    Did you find out why where is ignored?

  13. grigdevelop commented on May 17, 2020

    @grigdevelop

    You can also get entities with all relations.

         const repo = manager.getRepository(entityType);
         const relations = repo.metadata.relations.map(m => m.propertyName);
         const entities = await repo.find({ relations });
    
  14. 2 remaining items

  15. pvoisin commented on Aug 26, 2020

    @pvoisin

    The relation where only seems to work on id or perhaps primary columns,

    EG if your Car has user with JoinColumn() you could successfully query on where: { user: { id: 123 } } however it doesn't seem to work for non primary columns or joins such as the user's companyId

    How sad! I just confirmed that too (I'm not using annotations but the results are the same). Searching with something like the following doesn't work whilst using "branchId" (primary key) instead of "languageId" does work:

    where: {
      name: {
        languageId: 7,
      },
    }
    

    @niccolofanton - thanks for the snippet! It does the trick but, to me, having to rely on somewhat raw SQL defeats the ORM purpose a little...

  16. BenSjoberg commented on Nov 2, 2020

    @BenSjoberg

    Seems related to #2707

  17. nelsonsvo commented on Apr 21, 2021

    @nelsonsvo
    Contributor

    has finding an entity with relation condition been implemented?
    I think this is a necessity for an ORM

  18. pradeep0601 commented on Apr 26, 2021

    @pradeep0601

    Eagerly waiting for this feature to search based on relation fields other than the primary key.

  19. jeffersonlicet commented on May 15, 2021

    @jeffersonlicet

    Hi, is anyone working on this? I can take this issue and try to send a pull request.

  20. MardariG commented on Jun 14, 2021

    @MardariG

    Hi, is anyone working on this? I can take this issue and try to send a pull request.

    any status here?

  21. jeffersonlicet commented on Jun 14, 2021

    @jeffersonlicet

    Hi, is anyone working on this? I can take this issue and try to send a pull request.

    any status here?

    By default only JoinColumns are used (id) I'm trying to include relation cols in a non-intrusive way.

  22. Goldziher commented on Jun 17, 2021

    @Goldziher

    wow this is a bad bug

  23. jeffersonlicet commented on Jun 17, 2021

    @jeffersonlicet

    I'll adventure myself and send a non-optimized pull request so I can get feedback about a better way to do this. But seems like it's working now.

  24. salvationarinze commented on Jun 23, 2021

    @salvationarinze

    Any solution to this yet?

  25. imnotjames commented on Jun 23, 2021

    @imnotjames
    Contributor

    This is directly related to #2707. If that gets fixed, this does.

  26. locked and limited conversation to collaborators on Jun 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions