typeorm: Error: Cannot get entity metadata for the given alias

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

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 76
  • Comments: 48 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Works only with getRawMany()

For anyone having this issue in the same boat as me where I was camelCasing my entity name, changing to snake_case corrected the problem for me.

@Entity()
class FooBar {}
@EntityRepository(FooBar)
export default class FooBarRepository {
  ...
  update(data) {
    return this.manager.update('foo_bar', id, data) // this was `fooBar` and not working
  }
}

For anyone interested I was having this issue when using getMany but I fixed it by using getRawMany() instead

Ideally I’d like to use getMany since it’s harder to get the entity mapped with the raw results

Try this hack:

  query.expressionMap.mainAlias.metadata = query.connection.getMetadata(YourEntity)

Hope it will help someone

@pleerock A query builder that can’t nest queries is like a car with two wheels. Is this going to get fixed anytime soon?

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

// Breaks
orderBy('Users.type', 'ASC')


// Works
orderBy('type', 'ASC')

Using the info in this PR and this comment, I was able to use my subquery with entity mappings. It works with getMany.

I also had to emulate the way TypeORM was generating selects for my base entity (i.e. Entity.id becomes Entity_id).

It looks like this:

this.createQueryBuilder()
  .select('Event.id', 'Event_id')
  .addSelect('Event.fk_user_id', 'Event_fk_user_id')
  .from(subquery => {
    subquery.select('e.*').from(Event, 'e').offset(skip).limit(limit)
    // Subquery logic omitted here
  }, 'Event')
  .leftJoinAndSelect('Event.user', 'User')

query.expressionMap.aliases.splice(0, 1)
query.expressionMap.mainAlias.metadata = query.connection.getMetadata(Event);

const data = await query.getMany()

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.

same problem

Same issue. I suggest use repository.query("SQL");

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

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

Welcome! 🤙

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?

@PadraigGalvin Thanks It worked

Does anybody fixed this issue?. Could anybody post an explanatory Answer to this problem please.

Same here. Please infer the meta from the subselect. The SelectQueryBuilder when entityTarget instanceof Function knows the needed meta

Same problem

Same problem.

same problem here, any one fixed it?

Same problem.

Same problem, please help.