title: Doctrine join entities
body: <p>I'm trying to make some efficient improvements when querying for an entity which has a relationship to another entity.</p>
  
  <p>Entity A:</p>
  
  <pre><code>/**
   * @var integer
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  protected $id;
  
  /**
   * @var string
   * @ORM\Column(name="name", type="string", length=225)
   * @Assert\NotBlank(message="Please enter a name for your profile.")
   */
  protected $display_name;
  
  /**
   * @ORM\OneToOne(targetEntity="Posts", mappedBy="profile", cascade={"all"}, fetch="LAZY")
   */
  protected $posts;
  </code></pre>
  
  <p>Entity B:</p>
  
  <pre><code>/**
   * @var integer
   * @ORM\Column(name="profile_id", type="integer")
   * @ORM\Id
   */
  protected $profile_id;
  
  /**
   * @ORM\OneToOne(targetEntity="Profile", inversedBy="posts")
   * @ORM\JoinColumn(name="profile_id", referencedColumnName="id")
   */
  protected $profile;
  
  /**
   * @var string
   * @ORM\Column(name="content", type="string")
   */
  protected $content;
  </code></pre>
  
  <p>When I count the number of queries being executed I get two, I guess being doctrine runs two separate queries for each entity even through they have a relationship. </p>
  
  <p>I am  currently fetching entity A like so: </p>
  
  <pre><code>public function fetchById($id)
  {
      return $this-&gt;createQueryBuilder('p')
          -&gt;where('p.id = :id')
          -&gt;setParameter('id', $id)
          -&gt;getQuery()
          -&gt;getOneOrNullResult();
  }
  </code></pre>
  
  <p>And then calling entity B like so:</p>
  
  <pre><code> $profile = $profileRepository-&gt;fetchById($user-&gt;getUserId());
   $lastpost = $profile-&gt;getPosts()[0];
  </code></pre>
  
  <p>But I want to be able to join the second entity in this query so that I can just call one query rather than two. I was hoping to do something like this: </p>
  
  <pre><code>public function fetchById($id)
  {
      return $this-&gt;createQueryBuilder('p')
          -&gt;select('p','pp')
          -&gt;leftJoin(Posts::class, 'pp', \Doctrine\ORM\Query\Expr\Join::WITH, 'p.id = pp.profile_id')
          -&gt;where('p.id = :id')
          -&gt;setParameter('id', $id)
          -&gt;getQuery()
          -&gt;getResults();
  }
  </code></pre>
  
  <p>However the left join returns an array of two entities. This is not what I am wanting, because I want to still be able to call for example the getPosts() method in entity A.</p>
  
  <p>I essentially want to populate entity A, including all the related entities. But by only executing one query rather than two, is this possible in doctrine? </p>