Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2/Doctrine: load only subset of related entities

A Symfony2 application has a Job entity which has a tasks property, a collection of Task entities.

Job->getTasks() is used to iterate over a given job's collection of tasks. The Task entities encapsulated in the tasks property are lazy-loaded by Doctrine. I'm guessing they're loaded at the point getTasks() is called.

With extra details removed, the Job entity looks something like this:

<?php

class Job
{        
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\OneToMany(targetEntity="Example\Bundle\Entity\Task\Task", mappedBy="job")
     */
    private $tasks;

    public function __construct()
    {
        $this->tasks = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getTasks()
    {        
        return $this->tasks;
    }
}

I often need to access only a subset of all tasks (maybe 10 out of 1000) for a job and currently do so by iterating over getTasks() and picking out those with relevant ids.

For large collections of tasks (thousands, tens of thousands) it can take a long time for the tasks collection to be loaded from the database.

I'd like to reduce the time required to gain access to a subset of tasks. I can do so by using a custom entity repository to retrieve Task entities by id and job.

I'd like to know if a in-built feature of Symfony2 and/or Doctrine2 already exists for doing this.

My thinking is that an entity with a related collection of entities is a common situation (blog post and comments, for example) and that there may be some pagination-related concept at the entity level for retrieving only a subset of related entities.

Is there an in-built Symfony2 feature for what I need?

Update1:

I'd ideally like to be able to still iterate over Job->getTasks() knowing that it will return only a subset of tasks that I have somehow specified.

like image 586
Jon Cram Avatar asked Dec 30 '25 09:12

Jon Cram


1 Answers

I think you are looking for Extra Lazy Association.

like image 158
Mun Mun Das Avatar answered Jan 02 '26 04:01

Mun Mun Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!