Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 eager loading runs multiple queries instead of 1

I'm using Symfony2 with Doctrine2 (latest versions) and have this relation defined:

/**
 * @ORM\OneToMany(targetEntity="Field", mappedBy="event", fetch="EAGER")
 * @ORM\OrderBy({"name" = "ASC"})
 */
protected $fields;

The other side of the relation is defined as:

/**
 * @ORM\ManyToOne(targetEntity="Event", inversedBy="fields", fetch="EAGER")
 * @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
 */
protected $event;

When doing a "fetchOnyById", Doctrine runs 2 queries. 1 to fetch the object itself and 1 for the related fields. I would expect this to be a join, but it isn't.

When done in the controller, I pass my object to twig. There I retrieve the fields again as a property of the object. This causes another query to be run to retrieve the fields again.

Clearly I'm doing something wrong, as I would expect only 1 query to be run and 3 are actually run.

like image 476
DoppyNL Avatar asked Oct 21 '22 03:10

DoppyNL


1 Answers

I believe the reason this is occurring is because you're fetching entities, not a specific query. The idea of Doctrine is that you're fetching objects, not interacting with a database but an object resource as if they're all associated/referenced like stored entities. If you need a query like you're describing you would be better off using DQL but at that point you're not fetching entities created, you're getting a custom result.

I hope this made sense.

Basically the default association you're using is fetching associated objects not a joined query.

like image 83
Moylin Avatar answered Oct 27 '22 08:10

Moylin