我遇到了zend-db的问题,当我使用fetchall()
时,行返回重复,例如:
{
"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;
}
我想知道是什么产生了0
和1
。
顺便说一下,我正在学习Zf3,所以任何改进这些代码的技巧都非常受欢迎!
提前谢谢!
答案 0 :(得分:0)
老实说,我不知道错误的原因,但你可以这样解决:
安装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 packages:
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\ArrayObject;
use Zend\Hydrator\ArraySerializable;
参考: