2013-10-21 33 views
0

我有一个ContactsTable.php模块和功能如下:Zend2 TableGateway:如何获取一组数据

public function getContactsByLastName($last_name){ 
    $rowset = $this->tableGateway->select(array('last_name' => $last_name)); 
    $row = $rowset->current(); 
    if (!$row) { 
     throw new \Exception("Could not find row record"); 
    } 
    return $row; 
} 

这是确定的,但它只返回一行。 问题是在我的数据库中我有多个记录具有相同的姓氏,所以我的问题是: 如何返回一组数据?

我尝试这样做:

$where = new Where(); 
$where->like('last_name', $last_name); 
$resultSet = $this->tableGateway->select($where); 
return $resultSet; 

,但它不工作。

回答

3

,你希望你的第一个功能应该工作,只是删除线

$row = $rowset->current(); 

所以,完整的功能应该是这样的:

public function getContactsByLastName($last_name){ 
     $rowset = $this->tableGateway->select(array('last_name' => $last_name)); 

     foreach ($rowset as $row) { 
      echo $row['id'] . PHP_EOL; 
     } 
} 

更多信息,你可以在文档中找到http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html

0

您可以使用结果集来获取行数组:

public function getContactsByLastName($last_name) { 
     $select = new Select(); 
     $select->from(array('u' => 'tbl_users')) 
       ->where(array('u.last_name' => $last_name)); 

     $statement = $this->adapter->createStatement(); 
     $select->prepareStatement($this->adapter, $statement); 
     $result = $statement->execute(); 

     $rows = array(); 
     if ($result->count()) { 
      $rows = new ResultSet(); 
      return $rows->initialize($result)->toArray(); 
     } 

     return $rows; 
} 

它为我工作。