Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Two queries to fetch Category and sliced relationship
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 = :id';
$category = $em->createQuery($dql_category) /** @var Category $category */
->setParameter('id', $id)
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 = :category_id')
->setParameter('category_id', $id)
// we need to wrap in order for JMSSerializer to be able to traverse relationship
$array_collection = new ArrayCollection($presentations_array);
// 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
You can’t perform that action at this time.