Doctrine2 eagerly loads multiple requests instead of 1

I use Symfony2 with Doctrine2 (latest versions) and define this relationship:

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

The other side of the relationship is defined as:

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

When executing "fetchOnyById", Doctrine runs 2 queries. 1 to retrieve the object itself and 1 for related fields. I expect this to be a union, but it is not.

When this is done in the controller, I pass my object to the branch. There I again return the fields as a property of the object. This forces another query to be run to retrieve the fields.

It is clear that I am doing something wrong, as I expect only one request to be launched, and 3 are really running.

+4
source share
1 answer

I believe that the reason this happens is because you are retrieving objects, not a specific request. The idea of ​​Doctrine is that you retrieve objects without interacting with the database, but with the resource of the object, as if they were all linked / referred to as stored objects. If you need a query, as you describe, you will be better off using DQL, but at this point you are not creating the created objects, you will get a custom result.

Hope that made sense.

Basically, the association you use extracts related objects by default, rather than a combined query.

+3
source

Source: https://habr.com/ru/post/1496287/


All Articles