views:

1485

answers:

3

I have query in mysql:

SELECT * FROM (
    SELECT COUNT(*) AS count, t.name AS name
    FROM tag t
    INNER JOIN video_has_tag v USING (idTag)
    GROUP BY v.idTag
    ORDER BY count DESC
    LIMIT 10
) as tags ORDER BY name

and I want to write this in doctrine. How I can do that? I wrote:

Doctrine_Query::create()
        ->select('COUNT(t.idtag) as count, t.name')
        ->from('Tag t')
        ->innerJoin('t.VideoHasTag v')
        ->groupBy('v.idTag')
        ->orderBy('count DESC, t.name')
        ->limit(30)
        ->execute();

but I can't put it in "from" to sort by name.

+1  A: 

Doctrine cannot do a subquery in the FROM clause (nor can it JOIN to a subquery). Your current Doctrine query is going to sort by count and then by name. Is that not what you are wanting?

Brad
Now it's sort by count and when is the same value it's sort by name. I want to get standart tag cloud: 10 tags with greatest count sorted by name
snapshot
A: 

Doctrine will let you put a subquery in the FROM clause. However, it only can take DQL text statements in the subquery, you can't actually use another query object. If you rewrite your DQL subquery in textual form, you should be able to use it.

See this page of the documentation for an example. The example puts the DQL subquery in the WHERE clause, but it mentions that you can use subqueries in the FROM clause.

Thomas Albright
I wrote: $tags = Doctrine_Query::create() ->from('(SELECT COUNT(*) as count, t.name FROM Tag t INNER JOIN t.VideoHasTag v GROUP BY v.idTag ORDER BY count DESC LIMIT 30) as tags') ->orderBy('name') ->execute();and I get "Couldn't find class (SELECT "
snapshot
Doctrine does *NOT* support sub-queries in the FROM clause, despite what the docs say: http://groups.google.com/group/doctrine-user/browse_thread/thread/7572bf091e822b1f/d72952f5aa1378ee
EvanK
+3  A: 

This is a answer:

    $q = new Doctrine_RawSql();
    $q->addComponent('t', 'Tag')
      ->select('{t.name}, {t.count}')
      ->from('(SELECT COUNT(*) as count, t.name,t.idtag
        FROM Tag t
            INNER JOIN Video_Has_Tag v USING(idTag)
        GROUP BY v.idTag
        ORDER BY count DESC
        LIMIT 50) t')
      ->orderBy('name');
snapshot