Doctrine2 eager loading runs multiple queries inst

2020-03-25 01:17发布

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条回答
Summer. ? 凉城
2楼-- · 2020-03-25 01:45

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.

查看更多
登录 后发表回答