2013-07-07 67 views
6

在我的模型條件:在ZF2如何執行或在WHERE子句

$rowset = $this->tableGateway->select(array('username' => $identifier)); 
$row = $rowset->current(); 
return $row; 

它執行以下查詢:

SELECT * FROM member WHERE username='<< ENTERED VALUE >>'; 

,但我想執行以下查詢:

SELECT * FROM member WHERE username='<< ENTERED VALUE >>' OR id_customer='<< ENTERED VALUE >>'; 

我必須在模型文件中進行哪些更改?

並請建議有用的博客。我無法在ZF2文檔中找到答案。

回答

4

這樣做最簡單的方法是使用明確OR關鍵字:

$where = new Zend\Db\Sql\Where; 
$where->equalTo('username', $identifier); 
$where->OR->equalTo('id_customer', $customerId); 

$rowset = $this->tableGateway->select($where); 
$row = $rowset->current(); 
return $row; 
2

我已經與ZF 1更多的經驗比ZF 2所以可能還有其他的(更好的,更簡單的)解決方案,但是這應該做的伎倆:

// Manually build the Select object 
$select = $this->tableGateway->getSql()->select(); 

// Create array containing the fields and their expected values 
$conditions = array('username' => 'foo', 'id_customer' => 123); 

// Add these fields to the WHERE clause of the query but place "OR" in between 
$select->where($conditions, \Zend\Db\Sql\Predicate\PredicateSet::OP_OR); 

// Perform the query 
$rowset = $this->tableGateway->selectWith($select); 
3

有點遲到了,但爲了徹底我想我會提供相當奏效,我的選擇,以及一個可能是更容易一些,以實現對一些開發商:

// '$gateway' is a Zend\Db\TableGateway\TableGateway object... 
$search_string = 'something'; 
$select = $gateway->select(function($select) use($search_string) { 
    $select->where->OR->like('first_name', '%'. $search_string .'%'); 
    $select->where->OR->like('last_name', '%'. $search_string .'%'); 
}); 

運行後,$select將持有您的結果集,準備循環。

希望這可以幫助別人! :)