Question

I'm quite new to FLOW3 and I'm very new to Doctrine.

I'm just running some tests, and I want to learn or understand some techniques that I'll use later on. Now I'm stuck with this doctrine part where I want to generate some stats.

$results = $this->entityManager
    ->createQuery('SELECT version,count(version) 
        FROM (SELECT device, version 
            FROM \MyStuff\Stats\Domain\Model\Stat 
            WHERE 
                date > \'2011-10-01 00:00:00\' and 
                date < \'2011-10-02 00:00:00\' 
            GROUP BY device) GROUP BY version')
    ->getResult();

I asked at other places too, where they directed me to the Doctrine Docs. Well, now there are several examples but these 2 liners are trivial and I couldn't find any example related to that kind of subselect.
So I hope someone here can help me out.

Edit :
I'd like to solve this using dql.
I tried to solve this using a querybuilder but I was told that querybuilder != dql

Edit 2:
Now I was told that doctrine2 doesn't support subselects in "FROM (SUBSELECT)" but that it does "... WHERE IN (SUBSELECT)" and that one could rewrite my query to the IN () form. Well, trying to figure that out now.

Edit 3: I'm failing in rewriting the from-subquery into an in-subquery. So... dql doesn't do subqueries and there is no other way to do what I want with dql ?! Then dql would lack a very important feature I'd say. Or am I just not seeing sth. here ?

Edit 4: I finally got the in-subquery but it was about 10 times slower (4 seconds instead of 0.4) and now I was told by some doctrine guys from #doctrine, that I should use the nativeQuery function instead.

Edit 5: It works using the nativeQuery now, see my answer for that...

Was it helpful?

Solution

Using a native query it works like that...

$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addScalarResult('version', 'version');
$rsm->addScalarResult('count', 'count');
$results = $this->entityManager
    ->createNativeQuery(
        'SELECT version, COUNT(version) as count FROM
        (
            SELECT device, version 
            FROM mystuff_stats_domain_model_stat 
            WHERE 
                date > \'2011-10-01 00:00:00\' and 
                date < \'2011-10-02 00:00:00\' 
            GROUP BY device
        ) 
        as devices GROUP BY version',$rsm)
    ->execute();
echo var_dump($results,true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top