zf3 db - fetchall 返回重复的行

zf3 db - fetchall returning duplicated rows

我遇到 zend-db 问题,当我使用 fetchall() 时,行 return 重复,例如:

{
    "title"         : "Florianópolis",
    "neighborhoods" : [ {
                            "0"      : "6",
                            "1"      : "Abraão",
                            "name"   : "Abraão",
                            "number" : "6"
                        },
                        {
                            "0"      : "9",
                            "1"      : "Açores",
                            "name"   : "Açores",
                            "number" : "9"
                        },
                        {
                            "0"      : "5",
                            "1"      : "Agronômica",
                            "name"   : "Agronômica",
                            "number" : "5"
                        },

如您所见,我收到了两次他们的姓名和电话号码。这是获取信息的方法:

public function getNeighborhoodsByCity( $city )
{
    try
    {
        $this -> sql = new Sql( $this -> adapter );
        $select = $this -> sql -> select();
        $select -> from( $this -> table );
        $select -> columns( array( 'number',
                                   'name' ) );
        $select -> where( "city = '{$city}'" );
        $select -> order( "name" );
        $statement = $this -> sql -> prepareStatementForSqlObject( $select );
        $result = $statement -> execute() -> getResource() -> fetchall();
    }
    catch ( \Exception $e )
    {
        throw new \Exception ( 'ERROR : ' . $e -> getMessage() );
    }

    return $result;
}

我想知道是什么生成了 01。 顺便说一句,我正在学习 Zf3,所以非常欢迎任何改进此代码的提示! 提前致谢!

老实说,我不知道错误的原因,但是你可以这样解决:

安装 Hydrator 包(如果是 zf3):

$ composer require zendframework/zend-hydrator

替换您的代码:

$statement = $this -> sql -> prepareStatementForSqlObject( $select );
$result = $statement -> execute() -> getResource() -> fetchall();

收件人:

$statement = $sql->prepareStatementForSqlObject ( $select );
$result = $statement->execute ();

if (! $result instanceof ResultInterface || ! $result->isQueryResult ()) {
    return [ ];
}

$resultSet = new HydratingResultSet ( new ArraySerializable(), new ArrayObject() );
$resultSet->initialize ( $result );
return $resultSet;  

在头文件中包含 de 包:

use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\ArrayObject;
use Zend\Hydrator\ArraySerializable;    

参考:

zend-hydrator

hydrator Documentation

SQL Abstraction and Object Hydration