Warm tip: This article is reproduced from serverfault.com, please click

Doctrine: DQL query without specifying class fully qualified name (FQN)

发布于 2020-11-26 12:10:41

Is there a way to write DQL queries without specifying the fully qualified name of the class?

Is there a way to create the following query:

return $this->getEntityManager()->createQuery(
    'SELECT i
     FROM Company\AccountingBundle\Entity\Invoice i
     WHERE i.id = :id'
)->setParameter('id', 1)
    ->getResult();

Like this :

use Company\AccountingBundle\Entity\Invoice;
....

return $this->getEntityManager()->createQuery(
    'SELECT i
     FROM Invoice i
     WHERE i.id = :id'
)->setParameter('id', 1)
    ->getResult();

Or something similar. I really would avoid to set the full FQN in the DQL.

But I didn't find any "setClass" or another method to do this.

EDIT FOR CONTEXT

In fact, it is a Symfony project and the query is inside in a Repository class. I have a Doctrine XML definition of the entity, an entity and the entity repository also defined in the XML, but I always need to explicitly define the FQN, Any ideas?

Questioner
sdespont
Viewed
0
Jannes Botis 2020-11-30 01:19:11

Doctrine offers a way to alias entity namespaces to simpler, shorter names to be used in DQL queries or for Repository access.

You can set the alias of the entity namespace inside the Doctrine config of .yaml

doctrine:
  orm:
    auto_generate_proxy_classes: true
    naming_strategy: doctrine.orm.naming_strategy.underscore
    auto_mapping: true
    mappings:
        Company:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Company/AccountingBundle/Entity'
            prefix: 'App\Company\AccountingBundle\Entity'
            alias: AC

Then in the DQL, you can use "AC:Invoice":

return $this->getEntityManager()->createQuery(
  'SELECT i
  FROM AC:Invoice i
  WHERE i.id = :id'
  )->setParameter('id', 1)
  ->getResult();

References

Symfony bundle Mapping Configuration

Symfony Doctrine ORM Configuration