Skip to content

Instantly share code, notes, and snippets.

@dimkir
Last active February 4, 2016 09:20
Show Gist options
  • Save dimkir/b2d64f0f7b20c6715b76 to your computer and use it in GitHub Desktop.
Save dimkir/b2d64f0f7b20c6715b76 to your computer and use it in GitHub Desktop.
Two queries to fetch Category and sliced relationship
<?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