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?
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