Last active
February 4, 2016 09:20
-
-
Save dimkir/b2d64f0f7b20c6715b76 to your computer and use it in GitHub Desktop.
Two queries to fetch Category and sliced relationship
This file contains 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 | |
namespace AppBundle\Repository; | |
use AppBundle\Entity\Category; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Doctrine\ORM\EntityRepository; | |
use Doctrine\ORM\Tools\Pagination\Paginator; | |
class CategoryRepository extends EntityRepository | |
{ | |
/** | |
* Make several queries to load Category and slice of ManyToMany relationship | |
* to Presentation entity whist paginating the relationship. | |
* | |
* WARNING: In this implementation Category is "owned" (weak) side of the | |
* relationship. Thus if you try to flush the EntityManager, after calling | |
* this method, it will NOT follow Category->Presentation ManyToMany relationship | |
* and will NOT repersist it. However if in your implementation you will be | |
* returning "owning" side of the relationship - you may want to unregister | |
* this relationship with the EntityManager so that it can't be flushed anymore. | |
* | |
*/ | |
function getCategoryByIdWithGivenAmountOfPresentations($id, $limit = 5, $offset){ | |
$em = $this->getEntityManager(); | |
try { | |
$dql_category = 'SELECT cat FROM AppBundle:Category cat WHERE cat.id = :id'; | |
$category = $em->createQuery($dql_category) /** @var Category $category */ | |
->setParameter('id', $id) | |
->getSingleResult(); | |
} | |
catch(NoResultException $nrex){ | |
return null; | |
} | |
// also Presentation is owning side of the relationship, so it may be the case that | |
// this join wouldn't work the other way around | |
$presentations_array = $em | |
->createQuery('SELECT p,cat FROM AppBundle:Presentation p LEFT JOIN p.categories cat WHERE cat.id = :category_id') | |
->setFirstResult($offset) | |
->setMaxResults($limit) | |
->setParameter('category_id', $id) | |
->getResult(); | |
// we need to wrap in order for JMSSerializer to be able to traverse relationship | |
$array_collection = new ArrayCollection($presentations_array); | |
$category->setPresentations($array_collection); | |
// the problem here is that if anyone tries to flush this | |
// relationship, they may actually reset it... | |
return $category; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment