Last active
November 11, 2021 09:09
-
-
Save fhdalikhan/7bb3b414f28113fbe6b6c26389d9aa11 to your computer and use it in GitHub Desktop.
doctrine result set mapping for sql, this will map sql data to entity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// DQL example, however the result has to be mapped | |
$entityManager = $this->getEntityManager(); | |
$query = $entityManager->createQuery( | |
'SELECT nm.id AS nm_id, n FROM \App\Entity\Negotiation n | |
INNER JOIN n.messages nm WITH nm.id = (SELECT MAX(id) FROM \App\Entity\NegotiationMessage WHERE negotiation_id = n.id) | |
ORDER BY nm.id DESC' | |
)->setParameter('direction', EnumMessageDirectionType::TYPE_INBOUND); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// join on latest record for a many to one relation | |
$order = 'DESC'; | |
$sql = 'SELECT nm.id AS nm_id, n.* FROM `negotiation` n | |
INNER JOIN `negotiation_message` nm ON nm.negotiation_id = n.id | |
AND nm.id = (SELECT MAX(id) FROM negotiation_message WHERE negotiation_id = n.id AND nm.direction = \'INBOUND\') | |
ORDER BY nm.id ' . $order; | |
$rsm = new ResultSetMappingBuilder($this->getEntityManager()); | |
$rsm->addRootEntityFromClassMetadata('App\Entity\Negotiation', 'n'); | |
return $this->getEntityManager()->createNativeQuery($sql, $rsm)->getResult(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// manual result set mapping, the ResultSetMappingBuilder is better. | |
$rsm = new ResultSetMapping(); | |
$rsm->addFieldResult('n','id', 'id'); | |
$rsm->addFieldResult('n','email', 'email'); | |
$rsm->addFieldResult('n','currency', 'currency'); | |
$rsm->addFieldResult('n','cost_proposed', 'costProposed'); | |
$rsm->addFieldResult('n','cost_agreed', 'costAgreed'); | |
return $this->getEntityManager()->createNativeQuery($sql, $rsm)->getResult(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment