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?
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']
I managed to get alias with
$alias = current($builder->getDQLPart('from'))->getAlias();
(where $builder is an instance of Doctrine\ORM\QueryBuilder)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With