Zend Framework 2 和 SELECT count(*) 查询 [英] Zend Framework 2 and SELECT count(*) query

查看:15
本文介绍了Zend Framework 2 和 SELECT count(*) 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Zend Framework 2 执行这样的查询:

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]

...抛出以下错误:

Invalid column name 'count(*)'

这是由 count(*) 周围的方括号引起的.我怎样才能让它正常工作,基本上是在 SQL 中使用 count(*) 而不是 [count(*)] .另外,我知道您可以仅使用常规查询来完成此操作,但我需要使用它来处理 Select 对象.据我所知,这曾经适用于 Zend 的早期版本,我已经看到了很多解决方案,但对于 Zend Framework 2 没有任何解决方案.

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.

推荐答案

另一个论坛上的某个人很友好地为我解答了这个问题.做法是这样的:

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(*)')));

这篇关于Zend Framework 2 和 SELECT count(*) 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆