如何在ZF2中的tableGateway中使用having()

pol*_*dek 6 zend-framework2

如何在ZF2中使用having()子句?

网上几乎没有例子如何准备正确的选择对象.

我有这样的查询:

SELECT root_schema_id as `schema_id`
FROM `standard_specific_root_schemas`
WHERE `vehicle_id` IN (".implode(",",$vehiclesIds).")
GROUP BY `schema_id`, rootSubGroup_id HAVING count(*)=".$noOfVehicles
Run Code Online (Sandbox Code Playgroud)

而我正试图在ZF2中运行它:

public function getVehicleWithinCommonRootSubgroupInSpecific($vehiclesIds)
{
    $where = new Where();
    $where->in('vehicle_id', $vehiclesIds);

    $having = new Having('count(*) = '.count($vehiclesIds));

    $rowset = $this->tableGateway->select(function (Select $select) use ($where, $having) {
        $select
            ->where($where)
            ->having($having);
    });

    if (!$rowset) {
        throw new \Exception("Could not find schemas for group $groupId");
    }
    return $rowset;
}
Run Code Online (Sandbox Code Playgroud)

当然,ZF2中的那部分尚未完成,因为我想检查它是否先工作.我尝试过几种方法来提供params来获取方法,但是一切都会产生错误.

请帮忙,我很绝望......

Jaa*_*aar 6

我无法测试您的查询,但可以尝试重现您需要的查询.

我通过构造调整了必须使用 - > expression()而不是变量.我还添加了组声明.

为了查看查询,我添加了一个var_dump:

    $where = new \Zend\Db\Sql\Where();
    $where->in('vehicle_id', $vehiclesIds);

    $having = new \Zend\Db\Sql\Having();
    $having->expression('count(*) = ?', count($vehiclesIds));

    $rowset = $this->tableGateway->select(function (\Zend\Db\Sql\Select $select) use ($where, $having) {
        $select
            ->where($where)
            ->group(array('schema_id', 'rootSubGroup_id'))
            ->having($having);

        var_dump( $select->getSqlString() );
    });
Run Code Online (Sandbox Code Playgroud)

如果这有帮助,请告诉我.


为避免评论中提到的错误,您必须执行以下操作:

$sql = $this->tableGateway->getSql();

$select = $sql->select();

$where = new \Zend\Db\Sql\Where();
$where->in('vehicle_id', $vehiclesIds);

$having = new \Zend\Db\Sql\Having();
$having->expression('count(*) = ?', count($vehiclesIds));

$select
    ->where($where)
    ->group(array('schema_id', 'rootSubGroup_id'))
    ->having($having);

$preparedQuery = $sql->prepareStatementForSqlObject($select);

var_dump( $preparedQuery->getSql() );
Run Code Online (Sandbox Code Playgroud)

但是,如果我是对的,tableGateway会为您执行此操作,因此一旦您开始使用select来查询数据库,错误就会消失.

此外,您也可以使用上面的方法来做到这一点,只需替换它:

$preparedQuery = $sql->prepareStatementForSqlObject($select);

var_dump( $preparedQuery->getSql() );
Run Code Online (Sandbox Code Playgroud)

附:

$this->tableGateway->selectWith($select);
Run Code Online (Sandbox Code Playgroud)