2012-11-11 65 views
2

嗨,我正試圖抓住Zend 2,我在表格網關中的where子句有一些問題。Zend 2 - TableGateway Where子句

下面是我的表類:

//module\Detectos\src\Detectos\Model\OperatingSystemTable.php 
namespace Detectos\Model; 

use Zend\Db\TableGateway\TableGateway; 

class OperatingSystemsTable 
{ 

    public function findOs($userAgent) 
    { 

     $resultSet = $this->tableGateway->select(); 

     foreach ($resultSet as $osRow) 
     { 
      //check if the OS pattern of this row matches the user agent passed in 
      if (preg_match('/' . $osRow->getOperatingSystemPattern() . '/i', $userAgent)) { 
       return $osRow; // Operating system was matched so return $oses key 
      } 
     } 
     return 'Unknown'; // Cannot find operating system so return Unknown 
    } 
} 

的模型是像這樣:

class Detectos 
{ 
    public $id; 
    public $operating_system; 
    public $operating_system_pattern; 

    public function exchangeArray($data) 
    { 
     $this->id      = (isset($data['id']))        ? $data['id']      : null; 
     $this->operating_system   = (isset($data['operating_system ']))    ? $data['operating_system ']  : null; 
     $this->operating_system_pattern = (isset($data['operating_system_pattern']))  ? $data['operating_system_pattern'] : null; 

    } 

    public function getOperatingSystemPattern() 
    { 
     return $this->operating_system_pattern; 
    } 
} 

什麼我有工作,但我應該真的能像做:

public function findOs($userAgent) 
{ 

    $resultSet = $this->tableGateway->select()->where('operating_system_pattern like %' . $userAgent . '%'; 

} 

但我找不出正確的方法來做到這一點。

編輯(2012年12月11日07:53): 我試圖從薩姆的回答以下,但得到的錯誤:

$spec = function (Where $where) { 
    $where->like('operating_system_type', '%' . $this->userAgent . '%'); 
}; 


$resultSet = $this->tableGateway->select($spec); 

但得到了以下錯誤:

Catchable fatal error: Argument 1 passed to Detectos\Model\OperatingSystemsTable::Detectos\Model\{closure}() must be an instance of Detectos\Model\Where, instance of Zend\Db\Sql\Select given. 

我會還想補充一點,我已經閱讀了文檔並按照教程。沒有提及在那裏使用Zend \ Db \ Sql。我無法使用tableGateway中高級where子句的示例。我可能錯過了一些東西,但我不認爲這很明顯。

回答

9

爲什麼人們忽略了official documentation?該simples例子是這樣的:

$artistTable = new TableGateway('artist', $adapter); 
$rowset = $artistTable->select(array('id' => 2)); 

但是,你可以給select()函數Zend\Db\Sql\Where類型的參數。 this part of the official documentation再次幫助很多。隨着Where你可以做更乾淨的代碼,如:

$where = new Where();  
$where->like('username', 'ralph%'); 

$this->tableGateway->select($where) 

希望這可以幫助你一點。不要忽略文檔! ;)

+0

更新,顯然是匿名函數返回一個select語句而不是Where對象,我不知道。像這樣,它應該可以工作 – Sam

+0

不可以,致命錯誤:找不到類'Detectos \ Model \ Where'。當試圖做到:$ where = new Where(); –

+1

您需要'使用Zend \ Db \ Sql \ Where':S對不起,請不要提及它 – Sam