php 为什么列别名在学说中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3675703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:39:42  来源:igfitidea点击:

Why does column alias not work in doctrine?

phpsqldoctrine

提问by user443281

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:

生成的sql是:

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.

因此在执行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?

  1. 为什么是表的别名'i'而不是'p'

  2. 为什么'num_a'in have 子句没有替换为'i__0',如何解决?

Thanks for your suggestion...

谢谢你的建议...

采纳答案by DrColossos

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?

1:为什么表的别名是“i”而不是“p”?

2:为什么have子句中的'num_a'没有替换为'i__0',如何解决?

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.

这两个问题都得到了简单的回答:Doctrine 使用它自己的别名进行查询。您不需要知道这些别名,因为它们不会影响您,您也不需要使用它们。

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

即使 Doctrine 命名了别名,i__0您也可以使用自定义别名访问该属性,例如$yourObject->num_a将具有正确的值,即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.

查看查询的输出是一个有用的调试功能,但依赖于应用程序内部是没有意义的,因为这些值仅用于 Doctrine 的内部机制。

回答by Alan Smith

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:

我在设置别名时也遇到了问题。我必须设置别名,然后使用带有该别名的“ORDER BY”。以下解决方案对我有用:

$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.

在结果查询中看起来像“...() AS p_0 ... ORDER BY p_0”。我希望它会帮助某人。

回答by przemo_li

This would not be valid SQL.

这不是有效的 SQL。

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

SQL 标准声明 SELECT 将having. 所以你需要在having.

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

好建议。只要您使用 SQL 消费数据库,就尽可能地接近 SQL。