Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Doctrine does not load related entities in many-to-many relation

I have a many-to-many-relation, and when I load an entity that is on one side this relation, I expect to see as its property the ArrayCollection of related entities on another side. However, this does not happen - the ArrayCollection loaded has no elements in it, while in the database I can see the related entries. What could be the reason?

Here is my code:
One side of the relation, ConsolidatedReport class:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="P24\Response",  inversedBy="consolidatedReports")
 * @ORM\JoinTable(name="con_rprt_responses")
 */
private $responses;

Another side of the relation, Response class:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="P24\ConsolidatedReport\ConsolidatedReport", mappedBy="responses")
 */
private $consolidatedReports;

Here is the function I run to get an instance of ConsolidatedReport. This function sits inside a service that is being called from container:

/**
 * Picks the consolidated report with given id.
 *
 * @param string $id
 *
 * @return ConsolidatedReport
 *
 * @throws NonExistentConsolidatedReportException if the survey doesn't exist
 */
public function pick($id)
{
    $report = $this->repository->findOneBy(array('id' => $id));

    if (!$report) {
        throw new NonExistentConsolidatedReportException($id);
    }

    return $report;
}'

In the database, there is "con_rprt_responses" table with two columns "consolidated_reports_id" and "response_id". However, in profiler I do not see any queries to that table.

What could go wrong here?

UPDATE: Please see my answer to this question below, that worked for me.

like image 501
Vasily802 Avatar asked Aug 26 '15 20:08

Vasily802


1 Answers

I added fetch="EAGER" to the $responses property of ConsolidatedReport class, and it worked.

The code now looks like this:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="P24\Response", inversedBy="consolidatedReports", fetch="EAGER")
 * @ORM\JoinTable(name="con_rprt_responses")
 */
private $responses;

More info here: http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#by-eager-loading

Still if someone knows why the collection of related entity would not load without explicitly specifying EAGER fetching - please share your knowledge, it is highly appreciated!

like image 180
Vasily802 Avatar answered Nov 16 '22 02:11

Vasily802