Zend Framework 2 TableGateway MAX查询

时间:2015-09-08 14:44:11

标签: php mysql zend-framework zend-framework2

因为几天我使用tablegateway和zf2函数的mysql查询有问题。

我想获得列'reservation_spot'的最大值'reservation_datetime' = &reservation_datetime 查询应该像这样

SELECT MAX(`reservation_spot`) FROM `reservation` WHERE `reservation_datetime`='2015-09-30 8:00'

我已经尝试了很多东西来解决这个问题,但我不能

这是我的功能

public function getMaxValueWhereDate($reservation_datetime)
    {
        $select = $this->tableGateway->getSql()->select();
        $select->columns(array(
            'maxValue' => new Expression('MAX(reservation_spot)')
        ));
        $select->where(array('reservation_datetime' => $reservation_datetime));

        $rowset = $this->tableGateway->selectWith($select);
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not retrieve max value");
        }

        return $row;
    }

加上这个

$reservation->reservation_spot = $this->getMaxValueWhereDate($reservation_datetime);
$reservation->reservation_spot++;

在此之后,当我运行表单时,我收到错误:

  

无法执行声明(42000 - 1064 - 您输入错误   你的SQL语法;查看与MariaDB对应的手册   在''55','41','1',0附近使用正确语法的服务器版本,   '2015-09-08 16:23:27')'在第1行)

我的功能查询

SELECT MAX(reservation_spot) AS `maxValue` FROM `reservation` WHERE `reservation_date` = '2015-09-30 08:00'

@UPDATE解决,编辑为

public function getMaxValueWhereDate($reservation_datetime)
{
    $sql = $this->tableGateway->getSql();
    $select = $sql->select();
    $select->columns(array(
        'maxValue' => new Expression('MAX(reservation_spot)')
    ));
    $select->where(array('reservation_datetime' => $reservation_datetime));

    return $this->tableGateway->selectWith($select);
}

$reservation->reservation_spot = (int)$this->getMaxValueWhereDate($reservation_datetime);

2 个答案:

答案 0 :(得分:0)

您将返回行结果,该结果是模型的实例,而不是您想要的

在第一个示例中,更改此行:

return $row->maxValue;

您还必须在模型中声明maxValue字段,否则它将无法映射。

如果您在模型中不需要此字段,另一种可能性是使用现有字段:

$select->columns(array(
    'reservation_spot' => new Expression('MAX(reservation_spot)')
));

然后:

return $row->reservation_spot;

答案 1 :(得分:0)

$date = '2015-09-30 8:00';
$select = $this->getSql()->select()
           ->columns(array('Reservation ' => new \Zend\Db\Sql\Expression('MAX(reservation_spot)')))
           ->where("reservation_datetime ='$date'");
        $resultSet = $this->selectWith($select);
        $row = $resultSet->current();