我使用的是 ZendFramework 2 和 TableGateway,它们适用于普通的选择语句。但我似乎无法找到如何使用 ZendFramework 2 select 获得列的最大值。 我的选择应该看起来像
SELECT MAX( `publication_nr` ) AS maxPubNr FROM `publications`
我的代码如下:
use Zend\Db\TableGateway\TableGateway;
class PublicationsTable
{
protected $tableGateway;
...
public function getMaxPubicationNr()
{
$rowset = $this->tableGateway->select(array('maxPubNr' => new Expression('MAX(publication_nr)')));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not retrieve max Publication nr");
}
return $row;
}
最佳答案
如果您查看 TableGateway,您会注意到 Select 方法的参数实际上传递给了查询的 Where 部分,这使您的查询不正确。
您需要直接修改选择对象,因为 TableGateway 不会为您提供任何代理方法来执行此操作。
你可以尝试这样的事情:
public function getMaxPubicationNr()
{
$select = $this->tableGateway->getSql()->select();
$select->columns(array(
'maxPubNr' => new Expression('MAX(publication_nr)')
));
// If you need to add any where caluses you would need to do it here
//$select->where(array());
$rowset = $this->tableGateway->selectWith($select);
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not retrieve max Publication nr");
}
return $row;
}
我还没有测试过,但这应该能让你到达那里:)
你可能会遇到另一个问题,那是因为 TableGateway 试图从结果中为你构建一个对象,但你并没有带回一整行来构建一个对象,你只是带来了返回单个列。
我只想添加使用 Db/Select 对象来执行此操作,而不用担心 GateWay 老实说,我认为它不应该像这样使用。
关于select - zendframework 2 选择一列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17447311/