01/25/2016

Doctrine: joining entities with no association

Doctrine normally joins along a mapped association — ->join('a.user', 'u'). When there is no association between the two entities, you can still join them by naming the class and giving the condition yourself:

use Doctrine\ORM\Query\Expr\Join;

public function findHistoryFor(User $user): array
{
    return $this->createQueryBuilder('h')
        ->addSelect('u')
        ->leftJoin(
            User::class,
            'u',
            Join::WITH,
            'h.userId = u.id',
        )
        ->where('u = :user')
        ->setParameter('user', $user)
        ->orderBy('h.createdAt', 'DESC')
        ->getQuery()
        ->getResult();
}

Join::WITH is the part doing the work: it says "join this class on this condition" rather than "follow this mapping". User::class is worth preferring over the string 'User\Entity\User' — a typo in a class constant is a fatal error at the point you wrote it, and a typo in a string is a runtime exception somewhere else.

What the query gives you back, which is the part that surprises people

Selecting two entity aliases does not hand back History objects with a user property filled in. There is no association, so there is nowhere to put one. Tested on Doctrine ORM 3.7.6 (DBAL 4.5.1, PHP 8.3.36, SQLite), with two users and three history rows, the query above for one user returned a flat list of mixed entities:

History id=2, User id=1, History id=1

Three items for two matching rows: each History object, plus the User once, placed where it first appeared. It is not a list of [0 => History, 1 => User] pairs, so code that does $row[0] and $row[1] on each item fails on an object. Check instanceof before you rely on the order.

The array-of-arrays shape shows up when you mix an entity with a scalar field:

$rows = $em->createQuery(
    'SELECT h, u.name AS userName FROM History h LEFT JOIN User u WITH h.userId = u.id'
)->getResult();

$history  = $rows[0][0];            // the History entity
$userName = $rows[0]['userName'];   // 'Ada'

That was the case in the test: the first row had keys 0 and userName. Selecting only scalar fields (SELECT h.note, u.name ...) with getArrayResult() returned plain arrays such as {"note":"a1","name":"Ada"}.

If you drop addSelect('u') entirely, the join still filters correctly and you get plain History objects back, two of them in the test, which is often what you actually wanted and is cheaper.

A template doing {{ row.user.name }} on a mixed list fails for the same reason: there is no user on a History object. Either shape the result in the repository for the caller, or select only the root alias and look the users up separately.

When to fix the mapping instead

This technique earns its place against a schema you do not control: a legacy table, another team's database, a column that holds an id without a foreign key behind it. On a schema you own, an unassociated join is usually a missing #[ORM\ManyToOne] wearing a disguise, and mapping it properly gets you lazy loading, cascades and ->join('h.user', 'u') for free.

A useful tell: if you find yourself writing the same Join::WITH condition in three repositories, the relationship is real and the mapping is what is missing.

Questions this keeps raising

Why does my result mix History and User objects?

Because the query selects two entity aliases and there is no association to nest one under the other. In a test on Doctrine ORM 3.7.6 the result was a flat list, History, User, History, with the User listed once. Mixing an entity with a scalar field gives array rows instead. Dropping addSelect on the joined alias returns plain root entities and still filters by the join.

What is the difference between Join::WITH and Join::ON?

For an association join, WITH adds your condition to the mapped association's join condition. For an entity joined with no association, which is this article's case, both Join::WITH and Join::ON produced identical SQL in a test on Doctrine ORM 3.7.6, so WITH is the one Doctrine's own examples use and the safe default.

Can I do this with a plain DQL string?

Yes - "LEFT JOIN App\\Entity\\User u WITH h.userId = u.id" is the same query. The builder is preferable when parts of the query are conditional, and a DQL string is easier to read when it is not.

Should I add the association instead?

On a schema you own, usually yes. An unassociated join often means a missing ManyToOne, and mapping it gives you lazy loading and simpler queries. Keep the unassociated join for schemas you cannot change - legacy tables, or a database another team owns.