title: Lazy loading of Doctrine one-to-one associations
body: <p>I've been reading a lot about Doctrine lately and I have seen a general suggestion to avoid bi-directional One-To-One associations. <a href="https://tideways.io/profiler/blog/5-doctrine-orm-performance-traps-you-should-avoid" rel="nofollow">This page</a> (from June 2015) states:</p>
  
  <pre><code>... you should avoid bidirectional one-to-one associations in Doctrine. 
      The inverse side of a one-to-one association cannot be lazy loaded.
  </code></pre>
  
  <p>I am assuming that <em>cannot be lazy loaded</em> means something like <em>must be eager-loaded</em> .</p>
  
  <p>The page is also called "Doctrine Performance Traps", so it looks scary :)</p>
  
  <p>Since the <a href="http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-one-bidirectional" rel="nofollow">manual on one-to-one</a> doesn't mention this, I have decided to test and see for myself. I found a couple of classes in our test app that were already using one-to-one associations, so this was easy:</p>
  
  <pre><code>class Recipe
  {
      /**
       * @ORM\OneToOne(targetEntity="Image")
       * @ORM\JoinColumn(name="image_id", unique=true, referencedColumnName="id")
       */
      private $image;
  }
  
  class Image
  {
      /**
       * @ORM\OneToOne(targetEntity="Recipe")
       * @ORM\JoinColumn(name="recipe_id", referencedColumnName="id")
       */
      private $recipe;
  }
  </code></pre>
  
  <p>Next, I try to select an image in my controller:</p>
  
  <pre><code>$image = $em-&gt;getRepository('AppBundle:Image')-&gt;find(658);
  </code></pre>
  
  <p>In Symfony profiler I see one sql query with no joins. In the dumped image data, under Recipe, I see:</p>
  
  <pre><code>+__isInitialized__: false
  </code></pre>
  
  <p>Which would mean that the Recipe entity was lazy-loaded? </p>
  
  <p>The same happens when I load the Recipe: Image gets lazy-loaded. </p>
  
  <p>Adding <code>inversedBy</code> to any of the entities doesn't seem to make a difference.</p>
  
  <p>It seems that either the article I was reading was incorrect, or something has changed in Doctrine since then, or I don't understand lazy-loading.</p>
  
  <p>Questions:</p>
  
  <ul>
  <li>Can latest versions of doctrine lazy-load bidirectional one-to-ones?</li>
  <li>Why are bidirectional one-to-one associations so frequently considered harmful for performance?</li>
  </ul>
  
  <p>I understand that a lot of times I can get away without using bidirectional mapping, but sometimes I really really need to have them and I am just trying to understand the price of this decision.</p>
  
  <p>Thanks!</p>