Doctrine—select all fields and group by one of them
<p>I am trying to create a query with doctrine, which basically should look like that in SQL:</p>

<pre><code>SELECT p.* FROM some_tabel AS p GROUP BY p.type;
</code></pre>

<p>So I ended up with this, since this is closest this I found documented:</p>

<pre><code>private function getAll()
{
    //$this-&gt;em =&gt; Entity Manager
    return $this-&gt;em-&gt;createQueryBuilder()
        -&gt;select('p')
        -&gt;from('AppBundle:Robots', 'p')
        -&gt;groupBy('p.type')
        -&gt;getQuery()
        -&gt;getResult(Query::HYDRATE_ARRAY);
}
</code></pre>

<p>The error tells me that 'p.type' is not selected.</p>

<p>How can I get that working? </p>

<p><strong>UPDATE</strong></p>

<p>As mentioned in the accepted answer of <a href="https://stackoverflow.com/users/1580044/felippe-duarte">@Felippe Duarte</a>, it seems that the grouping of Mysql is a kind of wired. Even if I run: </p>

<pre><code>SELECT p.*, max(p.id) FROM some_tabel AS p GROUP BY p.type;
</code></pre>

<p>as suggested by many answers, the result is not what I expect, because only the first item of each type is included and no real grouping happens.</p>

<p>The option to order instead of grouping is good, but would still leave some processing to me, so it is redundant in this case.</p>

<p>Finally this code does what I need:</p>

<pre><code>private function groupByType(array $robots)
{
    return array_reduce($robots, 
        function($list, $robot)
        {
            $list[$robot-&gt;getType()][] = $robot;
            return $list;
        }, []);
}
</code></pre>

<p>Since this is not too much code and there wont be too many »Robots« I decided - following the KISS Paradigm - this to be the solution of choice.</p>