Skip to content

Error: Cannot get entity metadata for the given alias #4015

Closed

Description

@karinehovhannisyan

Issue type:

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

Database system/driver:

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

TypeORM version:

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

Steps to reproduce or a small repository showing the problem:
Hi. I'm having an issue with retrieving documents from a nested FROM-clause like this:

let query = getConnection().createQueryBuilder()
            .from((qb) => {
                    return qb
                        .from(A, "a")
                        .limit(1);
                }
                , "alias")

And get the error
Cannot get entity metadata for the given alias "alias".
Also, if I try to add another from:

.from(A, "b")

the query works, but the second FROM doesn't replace the first one, as specified in the docs. How can I do this the right way? Thanks

Activity

  1. tonivj5 commented on Jul 31, 2019

    @tonivj5

    I have the same problem, any help? 😢

  2. added a commit that references this issue on Aug 19, 2019
    4647790
  3. 0b3r commented on Aug 30, 2019

    @0b3r

    Same issue here. I tried doing the exact thing in the documentation (with my own schema) and it is not working.

    const userQb = await connection.getRepository(User)
        .createQueryBuilder("user")
        .select("user.name", "name")
        .where("user.registered = :registered", { registered: true });
    
    const posts = await connection
        .createQueryBuilder()
        .select("user.name", "name")
        .from("(" + userQb.getQuery() + ")", "user")
        .setParameters(userQb.getParameters())
        .getRawMany();
    

    Essentially, I am trying to wrap an existing query in another query to operate on the results and I am getting the same error. When I output the query string and execute it, it runs as expected but not in TypeORM.

    Has any one done this?

  4. yescsabi commented on Sep 10, 2019

    @yescsabi
  5. armin-th commented on Nov 14, 2019

    @armin-th

    Same problem here.

    For the moment I am running the raw query/params as a workaround as I do not need any special typeorm methods for running the query.

  6. xmsz commented on Nov 20, 2019

    @xmsz
  7. jimmdd commented on Jan 2, 2020

    @jimmdd
  8. sebapatr96 commented on Jan 16, 2020

    @sebapatr96
  9. dlarchikov commented on Jan 26, 2020

    @dlarchikov
  10. seandearnaley commented on Feb 6, 2020

    @seandearnaley
  11. volovodenko commented on Feb 18, 2020

    @volovodenko

    Works only with getRawMany()

  12. fullofcaffeine commented on Mar 15, 2020

    @fullofcaffeine
  13. abdullah2993 commented on Mar 19, 2020

    @abdullah2993
  14. erolkoseoglu commented on Mar 31, 2020

    @erolkoseoglu
  15. zpwebbear commented on Apr 14, 2020

    @zpwebbear

    I have the same problem

  16. 30 remaining items

  17. celxl commented on Jun 2, 2023

    @celxl

    funny fact getRawMany() works some times
    to don't get in to the query details just made it shorter and replace some values, but i think the point is clear

    await this.MyRepo.metadata.connection.createQueryBuilder()
        .select(`DISTINCT  some-value`)
        .from(`(${someQueryObject.getQuery()})` , 'subQ')
        .setParameters(someQueryObject.getParameters())
        .getRawMany()
          .then(result => {
           //this works just fine and result has the selected data
          });
          
    // thing is I actually need to total count so would like to do
    const q =  this.MyRepo.metadata.connection.createQueryBuilder()
        .select(`DISTINCT  some-value`)
        .from(`(${someQueryObject.getQuery()})` , 'subQ')
        .setParameters(someQueryObject.getParameters());
      
    const total = await q.getCount();  //so far so good
     await q.getRawMany()
           .then(res => {
            //and here is the error
           });
    
  18. vtereshyn commented on Oct 4, 2023

    @vtereshyn

    So, it's 2023 and the issue still exists. More over, with some workarounds it works in a wrong way. Is there any ETA on resolving this issue?

  19. nrathi commented on Oct 12, 2023

    @nrathi

    +1

  20. knovu commented on Dec 15, 2023

    @knovu

    @pleerock -> OrderBy with an alias name breaks our queries that have subqueries:

    // Breaks
    orderBy('Users.type', 'ASC')
    
    
    // Works
    orderBy('type', 'ASC')
  21. kawamura-vivit commented on Feb 20, 2024

    @kawamura-vivit

    Thanks knovu!! It solved the same problem I had.

  22. knovu commented on Feb 20, 2024

    @knovu

    Thanks knovu!! It solved the same problem I had.

    Welcome! 🤙

  23. parrotkesha commented on Mar 13, 2024

    @parrotkesha

    Hey everyone. If anyone still have this issue in 2024, I think I found a proper solution (at least for my case). I tried to use sub query in leftJoin and got this error.
    So, basically you need to assign a metadata manually to alias in the main query. Here is the example (I wanted to use LATERAL, which is not part of Typeorm functionality) :

               //ADD METADATA for productCollection alias (without it shows typeorm error 'Cannot get entity metadata for the given alias')
                const alias = new Alias();
                alias.type = 'join'
                alias.name = 'productCollection'
                alias.metadata = query.connection.getMetadata(ProductCollection)
                query.expressionMap.aliases.push(alias);
                
                //ADD LEFT JOIN with LATERAL construction by overriding getQuery function (HACK)
                query.leftJoin((qb) => {
                        qb.getQuery = () => 'LATERAL (SELECT * FROM "product_collection" "product_collection" WHERE "product_collection"."productId" = "product"."id" LIMIT 1)';
                        qb.setParameters({});
                        return qb;
                    },
                    'productCollection',
                        'TRUE'
                )

    Maybe it will help someone

  24. kasir-barati commented on Jan 1, 2025

    @kasir-barati

    Happy New Year TypeORM, its time for this issue to be solved as part of the Christmas gifts Santa Claus were supposed to give us all 🥹.

    image

  25. trannhan0810 commented on Mar 16, 2025

    @trannhan0810
    Contributor

    Maybe this PR will help , @imnotjames

  26. Creatium commented on Mar 20, 2025

    @Creatium

    I am having a very similar issue, but with getCount(). My query is similar to the original one in the first post: using subQuery inside from(), then using getRawMany() for the results with limit and also getCount() to get all results possible. But the getCount() throws this given alias error. Using only getRawMany() works as expected.

  27. henriquetroiano commented on Apr 5, 2025

    @henriquetroiano

    Congrats, it's 2025 and we keep on this issue. This is a 6-year issue!
    We ran into this issue everytime we need to use a subquery!

  28. hinogi commented on Apr 6, 2025

    @hinogi

    Congrats, it's 2025 and we keep on this issue. This is a 6-year issue! We ran into this issue everytime we need to use a subquery!

    not sure how far in the triage of all the old stuff is, but it could be that is planned. As you can see from the last 2 recent releases things are moving on.

  29. truesteps commented on May 9, 2025

    @truesteps

    Encountering the same issue using a subquery in .leftJoin

       qb.leftJoin(
          (subQuery) =>
            subQuery
              .from(Entity, 'et')
              .select([
                'et.id',
                'et.createdAt',
              ])
              .orderBy('et.createdAt', 'ASC'), // also tried only using createdAt instead of et.createdAt
          'entity',
          'entity.parentId = parent.id',
        )
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