Skip to content

Allow WHERE clause on joined columns. #2707

Closed

Description

@Techniv

Issue type:

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

Hi!

As it said in the documentation of FindManyOptions#where:

Querying a column from an embedded entity should be done with respect to the hierarchy in which it was defined.

It is possible to extend this capability to the joined columns ?

For exemple with 2 entities:

@Entity()
class Contact {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  name: string;
  @ManyToOne(type => Address)
  address: Address;
}

class Address {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  street: string;
  @Column()
  city: string;
}

Make a request like this:

contactRepository.find({
  relations: [ 'address' ],
  where: {
    address: {
      city: 'Paris'
    }
  }
});

SQL:

SELECT `Contact`.`id` AS `Contact_id`
    `Contact`.`id` AS `Contact_id`
    `Contact`.`name` AS `Contact_name`
    `Contact`.`addressId` AS `Contact_addressId`
    `Contact_address`.`id` AS `Contact_address_id`
    `Contact_address`.`street` AS `Contact_address_street`
    `Contact_address`.`city` AS `Contact_address_city`
  FROM `contact` `Contact`
  LEFT JOIN `address` `Contact_address`
    ON `Contact_address`.`id` = `Contact`.`addressId`
  WHERE `Contact_address`.`city` = "Paris";

I don't have seen any other options in TypeORM documentation to apply where clauses on joined columns. If there another way I am interested about it.

Thank you in advance for your help.

Activity

  1. periman2 commented on Aug 29, 2018

    @periman2

    @Techniv

    The way I do it is by using query builder like this:

    const findContract = await connection
    .getRepository(Contract)
    .createQueryBuilder("contract")
    .innerJoin("contract.address", "address")
    .where("address.city= :city", { city: "Paris" })
    .getOne();

    (innerJoin will NOT select the address entity so it will not be available in the contract.address received object, it will only query through the join, if you want to select it also then use leftJoinAndSelect instead of innerJoin)

    Let me know if this works for you.

  2. Techniv commented on Aug 30, 2018

    @Techniv
    Author

    Thanks for your help @periman2.
    But my needed is to filter result with a deep where clause by the find (or findMany) method in a generic service (model agnostic) where conditions are given from HTTP query parameters.

    So, I don't have any doubt about your solution with the query builder, but if it's possible, I prefer a solution where I don't need to make an ORM over an ORM. XD

    I will remember your proposition in last resort. But if there are a way to integrate this feature in TypeORM, it will be cool.

    Thank you again.

  3. periman2 commented on Aug 31, 2018

    @periman2

    @Techniv

    Well the cool thing about query builder is that it's just an object, you can pass it around and mutate it as you wish. Which means you can build generic methods that populate conditionally "qb.where" and "qb.andWhere" methods to the queryBuilder object using a requestDto model (which can have a number of filters and whatnot) . You can also extend this with any specific info you want to pass for specific models. That's how I'm actually using it in production.

    I do understand the need for having this somehow ready for us in the typeorm functionality though. It would be awesome!

  4. ocknamo-bb commented on Sep 6, 2018

    @ocknamo-bb
  5. Meg4mi commented on Sep 14, 2018

    @Meg4mi
  6. jun9358 commented on Feb 13, 2019

    @jun9358
  7. nadrane commented on Jun 3, 2019

    @nadrane

    Would the maintainers be willing to accept a PR that implements this functionality? It's a pretty common use case. I want to avoid to dropping down to the query builder because it's verbose and isn't type-safe (unless perhaps it can be and I'm missing something?).

  8. charmsRace commented on Jun 17, 2019

    @charmsRace

    I'm also strongly in support of this feature. I've developed an entire API using find, declaratively, instead of a query builder, only to find out that this extremely common use case is mysteriously absent.

    I think it's important to recognize that different developers have different styles & are optimizing for different things when they choose one or the other. These are the reasons I prefer not to use query builders (in descending order of importance, why not):

    A) It is extremely clunky & illegible to use in functional, declarative programming. My team's entire webapp is written functionally.
    B) It's not (as) type-safe. Locking this down is extremely important to me, especially in such an intrinsically type-unsafe process as DB record-fetching.
    C) It really can be quite verbose.

    Here's an example of query builder used functionally, with just three query parameters compared by basic equals.

      private getRecordsByQueryParams = async (queryParams: QueryParams) =>
        Object.keys(queryParams)
          .reduce((qb, param, i) => {
            const queryClause = `${User.ALIAS}.${param} = :${param}`;
            const value = { [param]: queryParams[param] };
    
            return i === 0
              ? qb.where(queryClause, value)
              : qb.andWhere(queryClause, value);
          }, (await connection).getRepository(User).createQueryBuilder(User.ALIAS))
          .getMany();

    Here's an actual API node from our app, with ten query parameters:

      private createQueryConditions = async ({
        id,
        type,
        name,
        geo,
        segment,
        industry,
        startIndex,
        stopIndex,
        stage,
        moment,
      }: QProps): Promise<FindManyOptions<AccountRecord>> => ({
        where: {
          ...(id === undefined ? {} : { id }),
          ...(type === undefined ? {} : { id: In(await this.getIdsForType(type)) }),
          ...(name === undefined ? {} : { name }),
          ...(geo === undefined ? {} : { geo }),
          ...(segment === undefined ? {} : { segment }),
          ...(industry === undefined ? {} : { industry }),
    
          ...(stage === undefined && moment === undefined
            ? {}
            : this.createMomentCondition({ stage, moment })),
        },
    
        ...this.createSliceConditions({ startIndex, stopIndex }),
      });

    Can you imagine trying to cram the (relatively simple!) conditional logic into the reducer callback, conditioning on the value of param? This is really the issue that comes up with method-chaining APIs -- when you need to conditionally call-or-not-call one of those methods. Like d3, which someone reaaally needs to rewrite for modern web.

  9. charmsRace commented on Jun 17, 2019

    @charmsRace

    Update: I did find a work-around for the issue in question here, although it's really hacky. I had the idea to use the Raw find operator to run an arbitrary query, e.g.

    const condition: FindManyOptions<ParentRecord>  = {
      where: {
        child: Raw(() => `SUBSTRING_INDEX(SUBSTRING_INDEX(${fieldName}, ',', ${i}), ',', -1) = ${moment}`),
      },
    };

    Here, fieldName is the name in the join table for the child entity field you want to query on (you can see this by enabling logging and checking the query). But of course, this relies on using the field name directly, which is quite brittle since TypeOrm has its own dynamic naming system. Also, since child was a joined field, it turns out TypeOrm straight-up ignored it, so I had to add a dummy field to the parent entity like so:

      @Column({
        type: boolean,
        nullable: true,
        select: false,
      })
      dummyField!: null;

    This is inelegant and error-prone... but it's the only timely alternative to rewriting large chunks of our API.

  10. Blacate commented on Sep 2, 2019

    @Blacate
  11. vytautas-pranskunas- commented on Sep 26, 2019

    @vytautas-pranskunas-
  12. saudar82 commented on Oct 7, 2019

    @saudar82
  13. jd1386 commented on Jan 15, 2020

    @jd1386
  14. m4kamran commented on Jan 20, 2020

    @m4kamran
  15. 69 remaining items

  16. WongYueKeung commented on Dec 2, 2021

    @WongYueKeung

    Any updates to add the same functionality to a one-to-many/many-to-one/many-to-many case? It is really frustrating just getting a Error: Cannot query across one-to-many for property testProp

    For those people who really want this feature there is a temporary way to do it
    (i am not sure if it would cause any bad conseuqnse)
    just comment out the /node_modules/typeorm/query-builder/QueryBuilder.js Line:881
    like this: //throw new Error("Cannot query across " + relation.relationType + " for property " + path);

    it seems working and no side effect was found yet, now I can fillter the relations in one-to-one and many-to-many query

  17. vixson commented on Oct 24, 2022

    @vixson

    Any updates to add the same functionality to a one-to-many/many-to-one/many-to-many case? It is really frustrating just getting a Error: Cannot query across one-to-many for property testProp

    Please in what case are you having this error?
    Because this mainly occurs when trying to update a deeply related entity via update method.
    Solution: Use save method instead and use the id as the updated condition. viola your issues would be solved

  18. AndreiSoroka commented on Mar 20, 2024

    @AndreiSoroka

    I didn't find in the documentation some info. Yesterday I lost the evening to find the solution how make ManyToOne like one of the Primary key.

    Thanks for this topic, it is my solution:

    @Entity({ name: "skipped_words" })
    export class SkippedWordEntity {
      @ManyToOne(() => UserEntity, (user) => user.id)
      @JoinColumn([
        {
          name: "userId",
          referencedColumnName: "id",
          foreignKeyConstraintName: "FK_skipped_words_user",
        },
      ])
      @PrimaryColumn({
        name: "userId",
        type: "text",
        primaryKeyConstraintName: "PK_skipped_words",
      })
      user!: string;
    
      @PrimaryColumn({
        type: "varchar",
        primaryKeyConstraintName: "PK_skipped_words",
      })
      word!: string;
    
      @PrimaryColumn({
        type: "varchar",
        length: 2,
        primaryKeyConstraintName: "PK_skipped_words",
      })
      language!: string;
    }

    But unexpectable, why I don't find it in documentation? It is a part of base functinonality

  19. cornzz commented on Oct 21, 2024

    @cornzz

    Came here from #4396, any updates?

  20. minikdev commented on Nov 20, 2024

    @minikdev

    why is this closed? the issue persists. It's almost 2025 guys...

  21. Bossieh commented on Dec 17, 2024

    @Bossieh

    Same, I bumped into this issue as well today.
    Allowing a where on joining relations would be very helpful in my case.

  22. samueljmacedo commented on Feb 5, 2025

    @samueljmacedo

    Leaving this comment here to bring attention to this again. Came from #4396 as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions