Let me start out with a tl;dr:
You don't have to do anything. The assumption above is wrong. Doctrine is clever enough to load the id fields into the proxy object (and only the id fields), so when you access it through the relationship, there will be no extra queries. I wanted to raise awareness to this, because I'm still receiving upvotes for my StackOverflow answer, which is incorrect. I'm not sure if this was added in a newer version, or it was my mistake when I checked the queries. So, to emphasize the point:
When you access a related entity's id, there will be no queries sent to the database, no matter if the entity was loaded eagerly, or lazily.
The problem
I'm trying to disperse the wrong assumption that other people may also have, or though about. The assumption, when you have an entity in hand, eg. you used $article = $em->find('Article', 1), and you access its related entity's id with $article->getCategory()->getId(), it will send two queries, one for for the Article model, and another for the Category model. This is wrong, there will be only one query!
Let's see some example code, with the following entities:
/** * @Entity */ class Article { /** * @Id * @GeneratedValue * @Column(type="integer") */ private $id; /** * @Column(type="string") */ private $title; /** * @ManyToOne(targetEntity="Category") */ private $category; } /** * @Entity */ class Category { /** * @Id * @GeneratedValue * @Column(type="integer") */ private $id; /** * @Column(type="string") */ private $name; /** * @OneToMany(targetEntity="Article", mappedBy="category") */ private $articles; }
We are going to register our SQL logger to check the queries that will be executed:
use Doctrine\DBAL\Logging\SQLLogger; class FileLogger implements SQLLogger { public function startQuery($sql, array $params = null, array $types = null) { echo "Executing SQL: $sql<br/>"; } public function stopQuery() { } }
And run the following code:
$emConfig = $em->getConfiguration(); $emConfig->setSQLLogger(new DC\FileLogger()); $article = $em->find('DC\\Entity\\Article', 1); $categoryId = $article->getCategory()->getId();
It will output "Executing SQL: SELECT t0.id AS id1, t0.title AS title2, t0.category_id AS category_id3 FROM Article t0 WHERE t0.id = ?. One, and only one query. Thank you for listening to this public service announcement.