Aldee
Aldee

Reputation: 4538

How to properly write Doctrine 2 DQL queries?

I have upgraded to Doctrine 2.2.2 now. I have managed to successfully connect my database to my application and was able to generate proxies and repositories. I have no problem with those generation. I am just confused with regards to using the DQL of doctrine 2.2.2. The case is this: I currently have a repository class responsible for user registration, authentication, etc. I have managed to execute the DQL on it but I just felt weird about this stuff (in my repository class).

$query = $em->createQuery("SELECT u FROM MyProject\\Entity\\AdminUsers u");

I tried also:

$query = $em->createQuery("SELECT u FROM AdminUsers u");

The last did not work but the first one works fine but it seems weird. Is it really the right way of executing DQL in doctrine 2? or am I missing something important.

NOTE: on the above declaration of this repository class is:

namespace MyProject\Repository;

use Doctrine\ORM\EntityRepository,
    MyProject\Entity\AdminUsers;

Upvotes: 3

Views: 3552

Answers (1)

BMBM
BMBM

Reputation: 16023

It almost is the right way to do it. If you would use single quotes ', you could just use a single backslash \ instead of a double backslash \\.

Doctrine cant find out (or it would be extremely expensive to do so) which classes you imported via use statements.

But you can use a typed repository which you retrieve from the entity manager via:

$repo  = $em->getRepository('MyDomain\Model\User');
$res = $repo->findSomeone();

And in the findSomeone() function you can do this:

$qb = $this->createQueryBuilder('u');
$dql = $qb->where('u.id = 1')->getDQL();

return $this->_em->createQuery($dql)->getSingleResult();

Meaning, the repository is already typed on your entity and knows which class to select from.

Some documentation:

Upvotes: 3

Related Questions