Zend Framework 2 and SELECT count(*) query

2019-04-04 14:35发布

I'm trying to do a query like this using 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 = 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.

3条回答
一纸荒年 Trace。
2楼-- · 2019-04-04 15:10

Could you try this code?

$this->num = $select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));

return $this->num;
查看更多
手持菜刀,她持情操
3楼-- · 2019-04-04 15:18

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(*)')));
查看更多
相关推荐>>
4楼-- · 2019-04-04 15:25

Yes, without new \Zend\Db\Sql\Expression('COUNT(*)'), just COUNT(*) leads to the following error statement:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'albs.COUNT(*)' in 'field list'

Having the

new \Zend\Db\Sql\Expression('COUNT(*)')

resolved it.

查看更多
登录 后发表回答