Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get doctrine2 table alias?

I want to create a method in my a Doctrine2 repository class that takes a QueryBuilder and adds some extra clauses, one of which is an inner join.

How can I find out the table alias that was used to instantiate the querybuilder? Is this something discoverable or should it be a convention across the codebase (and therefore a potential source of bugs)?

My client code is:

public function getPasswordAction($id)
{
    $user = $this->get('security.context')->getToken()->getUser();

    $repository = $this->getDoctrine()
        ->getRepository('TenKPwLockerBundle:Password');

    $query = $repository->createQueryBuilder('p')
        ->where('id = :id')
        ->setParameter('id', $id);

    $query = $repository->userCanReadRestriction($query, $user);
    ...

and my repository class contains:

public function userCanReadRestriction(\Doctrine\ORM\QueryBuilder $builder, \TenK\UserBundle\Entity\User $user)
{
                             // where can I get 'p' from?
    return $builder->innerJoin('p.shares', 's')
        ->where('createdBy = :creator')
        ->orWhere('s.toUser = :toId')
        ->setParameters(array('creator' => $user, 'toUser' => $user));
}

In fact, in the above code, how can I confirm that the QueryBuilder is working with the Password Entity at all?

like image 425
user1432227 Avatar asked Jun 06 '12 08:06

user1432227


2 Answers

The QueryBuilder object has two relevant methods: - getRootAliases() - getRootEntities()

Calling getRootAliases on a a QueryBuilder which has the from clause set will return an array of all aliases; similarly, calling getRootEntities will return an array of the shortened class names of the selected entities.

$qb = $em->createQueryBuilder();
$qb->from('BundleName:EntityName', 'entityName');

var_dump($qb->getRootAliases()); // returns ['entityName']
like image 180
Sam Dufel Avatar answered Oct 19 '22 23:10

Sam Dufel


I managed to get alias with

 $alias = current($builder->getDQLPart('from'))->getAlias();

(where $builder is an instance of Doctrine\ORM\QueryBuilder)

like image 22
Massimiliano Arione Avatar answered Oct 20 '22 00:10

Massimiliano Arione