title: Query Builder and Group By on two columns in Symfony2 / Doctrine generate duplicates
body: <p>I'm creating a message bundle where messages are grouped per contacts. On my index page, I display different threads. When you clic on one thread, it show all the messages exchanged between you and your contact. I use a Query Builder to display the threads on my index page:</p>
  
  <pre><code>$qb = $this-&gt;createQueryBuilder('m')
      -&gt;where('m.from = ?1 or m.to = ?1')
      -&gt;groupBy('m.to, m.from')
      -&gt;orderBy('m.date', 'DESC')
      -&gt;setParameter(1, $user-&gt;getId())
      -&gt;setMaxResults($pagination) // limit
      -&gt;setFirstResult($pagination * $page) // offset
  ;
  </code></pre>
  
  <p>If I have 3 entries, for exemple:</p>
  
  <pre><code>+----+------+----+
  | id | from | to |
  +----+------+----+
  | 1  | 1    | 2  |
  +----+------+----+
  | 2  | 2    | 1  |
  +----+------+----+
  | 3  | 1    | 2  |
  +----+------+----+
  </code></pre>
  
  <p>I expect:</p>
  
  <pre><code>+----+------+----+
  | id | from | to |
  +----+------+----+
  | 3  | 1    | 2  |
  +----+------+----+
  </code></pre>
  
  <p>But I get:</p>
  
  <pre><code>+----+------+----+
  | id | from | to |
  +----+------+----+
  | 2  | 2    | 1  |
  +----+------+----+
  | 3  | 1    | 2  |
  +----+------+----+
  </code></pre>
  
  <p>I found a way to do it with SQL, using the same alias for from_id and to_id:</p>
  
  <pre><code>SELECT id, from_id as c, to_id as c FROM Message WHERE c = 1 GROUP BY from_id, to_id
  </code></pre>
  
  <p>But I don't know how to do it with Doctrine.</p>
  
  <p>EDIT:</p>
  
  <p>Until I get a better idea, I use a key to easily "group by".</p>
  
  <pre><code>// entity
  
  /**
  * @ORM\Column(name="key", type="string", length=40)
  */
  private $key;
  
  /**
   * @ORM\PrePersist()
   */
  public function setOnPrePersist()
  {
      if($this-&gt;from &lt; $this-&gt;to) {
          $key = $this-&gt;from . 't' . $this-&gt;to;
      } else {
          $key = $this-&gt;to . 't' . $this-&gt;from;
      }
  
      $this-&gt;key = $key;
  }
  
  // query builder
  
  $qb = $this-&gt;createQueryBuilder('m')
      -&gt;where('m.from = ?1 or m.to = ?1')
      -&gt;groupBy('m.key')
      -&gt;orderBy('m.date', 'DESC')
      -&gt;setParameter(1, $user-&gt;getId())
      -&gt;setMaxResults($pagination) // limit
      -&gt;setFirstResult($pagination * $page) // offset
  ;
  
  return $qb-&gt;getQuery()-&gt;getResult();
  </code></pre>