2017-04-11 69 views
0

我在與Zend-dB的問題,當我使用fetchall(),恢復各行重複,例如:ZF3 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; 
} 

我想知道是什麼產生了01。 順便說一句,我正在學習Zf3,所以任何提示,以改善這個代碼是多餘的歡迎! 在此先感謝!

回答

0

老實說,我不知道該錯誤的原因,但你可以解決它像這樣:

安裝保溼包(如果是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; 

包括取消在頭文件包:

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

參考:

zend-hydrator

hydrator Documentation

SQL Abstraction and Object Hydration