Search code examples
symfonydoctrine-ormdoctrine-native-query

Doctrine hydrate only single row from native query


Here is my mappings:

$rsm = new ResultSetMapping;
$rsm->addEntityResult('OOHMediaBundle:OfferItem', 'i');
    $rsm->addFieldResult('i', 'reserved_at', 'reservedAt');

$rsm->addJoinedEntityResult('OOHMediaBundle:Offer', 'o', 'i', 'offer');
    $rsm->addFieldResult('o', 'o_id', 'id');
    $rsm->addFieldResult('o', 'continue_from', 'continueFrom');
    $rsm->addFieldResult('o', 'continue_to', 'continueTo');

Here is my native query:

$qb = $this->registry->getEntityManager()->createNativeQuery(
    'SELECT i.reserved_at, o.id AS o_id, o.continue_from, o.continue_to
    FROM offer_item AS i
    LEFT JOIN offers AS o ON i.offer_id = o.id
    WHERE i.reserved_at IS NOT NULL
    ;',
    $rsm
);

If above SQL is copied into mysql client it produce 43 records.

When executed as $qb->getArrayResult(); it only return 1 record.

When executed as $qb->getResult(); it return exception:

[Symfony\Component\Debug\Exception\ContextErrorException]  
Notice: Undefined index: offer_id 

Where other 42 records disappeared?


Solution

  • All right, as I mentioned in my comment, when using ResultSetMapping the Auto Increment column of the main entity needs to be listed in the field set result. The following should also apply for every join clause that needs to be added, so that doctrine can format the result properly.

    The order of the columns added with addFieldResult() have to be same as the one listed in the RAW query.

    The following chapter Examples in Doctrine's documentation contains some nice samples for further reference.