Aggregate values in Doctrine_RawSql queries

2019-05-06 23:24发布

问题:

Is it possible to use aggregate values in Doctrine_RawSql query? Here's what I'm trying to do:

$q = new Doctrine_RawSql();
$q->select('{q.*}, AVG(a.value) AS avg');
$q->from('-- complex from clause');
$q->addComponent('q', 'Question');

However, SQL created by Doctrine leaves only columns from table question and omits aggregate value avg.

回答1:

I've never used Doctrine_RawSql before, but I have done raw SQL queries through Doctrine using either of these two methods:

Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc("YOUR SQL QUERY HERE");

and

$doctrine = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$result = $doctrine->query('YOUR SQL QUERY HERE');

It seems like these two methods would leave your original SQL intact.

I should note that I'm using Doctrine 1.2 within the context of Symfony 1.4 applications, but AFAIK, this would work for you regardless of what other frameworks you may be using.



回答2:

Have you looked at the doctrine cookbook section on aggregates? They use createQuery method on the entity manager rather than RawSql objects.

I'm no expert with doctrine, but this could be a good place to start!



回答3:

Try putting the aggregate field in the SQL and then fetch it using curly brackets. I'm using SQL subquery.

$q = new Doctrine_RawSql();
$q->select('{s.*}, {s.avg} AS avg');
$q->from('(SELECT q.*, AVG(value) AS avg FROM Question AS q) AS s');
$q->addComponent('s', 'Question');

It works for me.