5
votes

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.

1
Basically the idea is not to think like you're working with SQL but to think like you're working with objects with real associations and letting Doctrine load and create those situations. If you come to a situation though where you need a joined query, it can be easily created with DQLMoylin

1 Answers

3
votes

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.