ZF2 大于/小于查询

ZF2 Greater than / Less than query

SQL 查询

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'));
    });

您需要使用 Predicate 对象,因为您要使用运算符:在本例中为 <=>=。您可以通过使用 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);