Why does column alias not work in doctrine?

限于喜欢 提交于 2020-01-21 06:37:08

问题


My script is like this:

$query = Doctrine_Query::create ()
  ->select('count(p.product_id) as num_a')              
  ->from ( 'ProductComments p' )
  ->groupBy('p.product_id')
  ->having('num_a =2 ');

And the generated sql is:

SELECT COUNT(i.product_id) AS i__0 FROM productcomments i GROUP BY i.product_id HAVING num_a=2

Thus I get an error when execute the sql.

I have two questions:

  1. why is the alias of the table 'i' instead of 'p'?

  2. why is the 'num_a' in having clause not replaced with 'i__0',how to fixed it?

Thanks for your suggestion...


回答1:


1: why is the alias of the table 'i' instead of 'p'?

2: why is the 'num_a' in having clause not replaced with 'i__0',how to fixed it?

Both questions are simply answered: Doctrine uses it's own aliases for the query. You do no need to know these aliases since they will not affect you nor will you need to work with it.

Even though Doctrine names the alias i__0 you can access the attribute with your custom alias, e.g. $yourObject->num_a will have the proper value, namely the result of count(p.product_id).

To see the output of your query is a useful debug feature, but relying on in inside your application is non-sense since these values are only used for the internal mechanisms of Doctrine.




回答2:


I also had a problem with setting alias. I had to set alias and then use "ORDER BY" with that alias. Following solution worked for me:

$myQuery->addSelect('(<my select>) AS my_alias');
$myQuery->orderBy('my_alias');

In the result query looked like "...() AS p_0 ... ORDER BY p_0". I hope it will help someone.




回答3:


This would not be valid SQL.

SQL standard state that SELECT will be logically executed after having. So You need to repeat aliased code in having.

Good advice. As long as You work with SQL consuming DBs stick as closely to SQL as possible.



来源:https://stackoverflow.com/questions/3675703/why-does-column-alias-not-work-in-doctrine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!