我在Symfony 1.4和Doctrine 1.2 ORM中构建了一个应用程序。我对ORM的学说非常陌生,我正在掌握它,但我无法完全解决这个问题。Symfony Doctrine按子查询计算排名后查询的查询
我有一个用户分数表(mbScoreByGenre),其中一个用户id可以有一个parent_genre的用户分数的多个记录。即 - 多对多
我的目标是根据给定的parent_genre_id和user_id的累积分数找到特定用户的排名。我的排名算法使用了一个子查询,并且在构建可用的学说查询时遇到了很多麻烦。
这里是我的mbScoreByGenre主义模式
mbScoreByGenre:
actAs:
Timestampable: ~
columns:
id: { type: integer, primary: true, autoincrement: true }
user_id: { type: integer, notnull: true }
genre_id: { type: integer, notnull: true }
parent_genre_id: { type: integer, notnull: true }
score: { type: float, notnull: true, default: 0 }
答:首先我试图做这样的事情:
$q = Doctrine_Query::create()
->select('((SELECT COUNT(1) AS num
FROM
(SELECT SUM(mbScoreByGenre.score)
WHERE SUM(mbScoreByGenre.score) > SUM(s.score)
AND mbScoreByGenre.parent_genre_id = '.$genre['parent_id'].'
AND s.parent_genre_id = '.$genre['parent_id'].'
GROUP BY mbScoreByGenre.user_id
) + 1) AS rank')
->from('mbScoreByGenre s')
->where('s.user_id = ?', array($user_id))
->groupBy('s.user_id')
->orderBy('rank');
but I got the following error Fatal error: Maximum function nesting level of '100' reached, aborting! in \lib\vendor\symfony-1.4.14\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Query\Tokenizer.php on line 303. I don't understand how to build the subquery so that it works.
B.于是我改变,尝试了不同的方法
$q = new Doctrine_RawSql();
$q ->addComponent('s', 'mbScoreByGenre')
->select('COUNT({*}) AS {rank}')
->from('(SELECT SUM(s.score) AS total_score
FROM mb_score_by_genre s
WHERE s.parent_genre_id = '.$genre['parent_id'].'
GROUP BY s.user_id)
')
->where('total_score >= (
SELECT SUM(s.score)
FROM mb_score_by_genre s
WHERE s.parent_genre_id = '.$genre['parent_id'].'
AND s.user_id = '.$user_id.'
GROUP BY s.user_id
)');
但是我得到这个错误:Sql查询中所有选定的字段必须是格式tableAlias.fieldName。我使用Doctrine_RawSql的原因是我读了1.2版的Doctrine不支持From中的子查询。对于这种方法,我无法弄清楚如何引用tableAlias.fieldName格式中的“total_score”列。我是否必须添加一个空白组件来引用返回的“total_score”子查询表?
C.最后,我试图运行子查询作为教条查询,并通过计算查询返回的doctrine对象行来计算排名。
$q = Doctrine_Query::create()
->select('SUM(s.score)')
->from('mbScoreByGenre s')
->where('s.parent_genre_id = ?', $genre['parent_id'])
->andWhere('SUM(s.score) > (
SELECT SUM(p.score)
FROM mbScoreByGenre p
WHERE p.parent_genre_id = '.$genre['parent_id'].'
AND p.user_id = '.$user_id.'
GROUP BY p.user_id
)')
->groupBy('s.user_id');
$result = $q->execute();
但它给我的错误:
SQLSTATE[HY000]: General error: 1111 Invalid use of group function. Is it because groupBy('s.user_id') and GROUP BY p.user_id, both p and s refer to the same model?
我做了一吨精练答案的网页,但我似乎无法找到任何的3种方法的答案。
任何帮助将是伟大的。欣赏它。
51次,并没有任何反应?我能做些什么来使问题更清楚?任何帮助将非常感激。 – frankp221 2012-04-04 00:07:53