Skip to content

Instantly share code, notes, and snippets.

@fhuitelec
Last active October 12, 2017 13:57
Show Gist options
  • Save fhuitelec/e6ea41415c06f0e509d09621668e9941 to your computer and use it in GitHub Desktop.
Save fhuitelec/e6ea41415c06f0e509d09621668e9941 to your computer and use it in GitHub Desktop.
[Query builder Doctrine] For lazy entity/relationship mapping #symfony #doctrine
<?php
namespace Super\Duper\Namespace;
use Bread\Namespace;
use Corn\Namespace;
use Entity\Namespace;
class DoctrineRepository extends EntityRepository
public function getEntity()
{
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addEntityResult(Entity::class, 'e');
$rsm->addFieldResult('e', 'id', 'myId');
$rsm->addFieldResult('e', 'some_external_id', 'externalId');
$rsm->addFieldResult('e', 'name', 'name');
$rsm->addJoinedEntityResult(Bread::class , 'br', 'e', 'entity_bread');
$rsm->addFieldResult('br', 'id', 'myId');
$rsm->addFieldResult('br', 'some_external_id', 'externalId');
$rsm->addFieldResult('br', 'type', 'type');
$rsm->addJoinedEntityResult(Corn::class , 'c', 'e', 'entity_corn');
$rsm->addFieldResult('c', 'id', 'myId');
$rsm->addFieldResult('c', 'has_popped', 'popped');
$sqlQuery = '
SELECT
-- Entity
e.id,
e.yolo_id AS some_external_id,
e.name
-- Bread
br.id,
br.yolo_id AS some_external_id,
br.type,
-- Corn
c.id,
c.has_popped
FROM public.entities AS e
-- Breads
INNER JOIN public.breads AS br
ON br.id = e.bread_id
-- Join table on bread and corns
INNER JOIN public.bread_has_corns AS bhc
ON bhc.bread_id = br.id
-- Corns
INNER JOIN public.corns AS c
ON c.id = corn_id
GROUP BY
e.id, e.yolo_id, e.name,
br.id, br.yolo_id, br.type,
c.id, c.has_popped
';
$query = $this->getEntityManager()->createNativeQuery($sqlQuery, $rsm);
$entities = new Entities($query->getResult()); // First-class collection - optional ofc
return $prospectAgencies;
}
}
?>
Entity\Namespace:
type: entity
repositoryClass: \Super\Duper\Namespace\DoctrineRepository
id:
myId:
column: id
type: super_id
fields:
externalId:
type: external_id
name:
type: string
oneToOne:
bread:
targetEntity: Bread\Namespace
manyToMany:
corn:
targetEntity: Corn\Namespace
Bread\Namespace:
type: entity
id:
myId:
column: id
type: bread_id
fields:
externalId:
type: external_id
type:
type: string
Corn\Namespace:
type: entity
id:
myId:
column: id
type: corn_id
fields:
popped:
type: boolean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment