2017-07-28 64 views
1

SQL查詢大ZF2低於/高於查詢不到

Select * FROM table_name 
WHERE category = 'category_name' 
AND created < 'todays_date' 
AND created > 'yesterdays_date' 

還需要添加ORDER和LIMIT條件。 如何在ZF2中實現這一點?

我有這樣的代碼:

$rowset = $this->tableGateway->select(function ($select) { 
     $select->where(['category' => $this->category]); 
     $select->order('id Desc'); 
     $select->limit($this->limit); 

     $DBtimeNow = new \DateTime(); 
     $select->lessThanOrEqualTo("created", $DBtimeNow->format('Y-m-d H:i:s')); 
     $DBtimeNow->sub(new DateInterval('P1D')); 
     $select->greaterThanOrEqualTo("created", $DBtimeNow->format('Y-m-d H:i:s')); 
    }); 

回答

1

你需要爲你想使用運營商使用謂詞對象:在這種情況下<=>=。您可以通過使用ZF2的Zend\Db這個組件Zend\Db\Sql\Where來獲得這些信息,因爲它擴展了Zend\Db\Sql\Predicate。然後我們可以在需要時使用這些操作員。請查看以下內容:

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

// here is the catch 
$predicate = new \Zend\Db\Sql\Where(); 

$select->where(['category' => $this->category]); 

// now use thus 
$DBtimeNow = new \DateTime(); 
$select->where($predicate->lessThanOrEqualTo("created", $DBtimeNow->format('Y-m-d H:i:s')), 'AND'); 
$DBtimeNow->sub(new DateInterval('P1D')); 
$select->where($predicate->greaterThanOrEqualTo("created", $DBtimeNow->format('Y-m-d H:i:s')), 'AND'); 

$select->order('id Desc'); 
$select->limit($this->limit); 

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