I'm trying to do a query like this using Zend Framework 2:
我正在尝试使用Zend Framework 2进行这样的查询:
SELECT count(*) as num FROM mytable
Here's the code I'm using to build my select statement (bear in mind I've imported the necessary classes):
这是我用来构建select语句的代码(请记住我已经导入了必要的类):
$select = new Select();
$select->from('mytable')
->columns(array('num'=>'count(*)'), false);
This code doesn't work because the resulting query is as follows:
此代码不起作用,因为生成的查询如下:
SELECT [count(*)] AS [num] FROM [mytable]
...which throws the following error:
...抛出以下错误:
Invalid column name 'count(*)'
This is caused by the square brackets around count(*). How can I get this to work properly, basically to have count(*) instead of [count(*)] in the SQL. Also, I know that you can do it with just a regular query, but I need this to work with the Select object. As far as I know, this used to work with the previous versions of Zend, I've seen plenty of solutions for those, but nothing for Zend Framework 2.
这是由count(*)周围的方括号引起的。我怎样才能使它正常工作,基本上在SQL中使用count(*)而不是[count(*)]。另外,我知道你可以只使用常规查询来完成它,但我需要这个来处理Select对象。据我所知,这曾经与Zend的早期版本一起使用,我已经看到了很多解决方案,但Zend Framework 2没有。
3 个解决方案
#1
39
Somebody on another forum was kind enough to give me the answer for this. This is how it's done:
另一个论坛上的人很友善地给我答案。这就是它的完成方式:
$select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
#2
4
Yes, without new \Zend\Db\Sql\Expression('COUNT(*)')
, just COUNT(*)
leads to the following error statement:
是的,没有新的\ Zend \ Db \ Sql \ Expression('COUNT(*)'),只有COUNT(*)会导致以下错误声明:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'albs.COUNT(*)' in 'field list'
SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'albs.COUNT(*)'
Having the
new \Zend\Db\Sql\Expression('COUNT(*)')
resolved it.
#3
0
Could you try this code?
你能试试这段代码吗?
$this->num = $select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
return $this->num;
#1
39
Somebody on another forum was kind enough to give me the answer for this. This is how it's done:
另一个论坛上的人很友善地给我答案。这就是它的完成方式:
$select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
#2
4
Yes, without new \Zend\Db\Sql\Expression('COUNT(*)')
, just COUNT(*)
leads to the following error statement:
是的,没有新的\ Zend \ Db \ Sql \ Expression('COUNT(*)'),只有COUNT(*)会导致以下错误声明:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'albs.COUNT(*)' in 'field list'
SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'albs.COUNT(*)'
Having the
new \Zend\Db\Sql\Expression('COUNT(*)')
resolved it.
#3
0
Could you try this code?
你能试试这段代码吗?
$this->num = $select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
return $this->num;