Symfony & Doctrine: Using table joins with unassociated entities

In Symfony using Doctrine, if no association is available for two entities, you can still join them and treat them like they have a relationship.  To do so, you have to use the “Join: WITH” method.  Here’s an example query to illustrate, notice the “a.user = u.id”.

public function getHistory($users) {

    $qb = $this->entityManager->createQueryBuilder();
    $qb ->select('a', 'u')
        ->from('Credit\Entity\UserHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Some other helpful links on Stack Overflow:

http://stackoverflow.com/questions/15087933/how-to-do-left-join-in-doctrine

http://stackoverflow.com/questions/19185587/left-join-on-condition-and-other-condition-syntax-in-doctrine/19189240#19189240

Here’s a great reference for advanced Doctrine queries:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#high-level-api-methods

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *