php zf2 select where clause with SQL function

2019-09-12 07:57发布

问题:

I need to compare DATE format from a DATETIME.

Prior ZF 2.3.5, the following code was working fine:

    $select->where('DATE(arrival_date) <= DATE(NOW())');
    $select->where('DATE(departure_date) >= DATE(NOW())');
    $select->where('enable = true');

With ZF 2.4.2+ it does not work anymore and produce the following error:

Cannot inherit previously-inherited or override constant TYPE_IDENTIFIER from interface Zend\Db\Sql\Predicate\PredicateInterface

I have tried the following (without error). The problem is that "arrival_date" is a DATETIME format, and I need to compare with a DATE only.

    $where = new Zend\Db\Sql\Where();
    $where->lessThanOrEqualTo('arrival_date', date('Y-m-d'));
    $where->greaterThanOrEqualTo('arrival_date', date('Y-m-d'));
    $where->equalTo('enable', true);
    $select->where($where);

Ideally, this code should work, but it does not:

        $select->where(new Zend\Db\Sql\Predicate\Expression('DATE(arrival_time) <= ?', 'DATE(NOW())'));

I am lost, any idea ?

回答1:

Just use Expression like this:

    $select->where(
        array(
            new \Zend\Db\Sql\Predicate\Expression("DATE(arrival_date) <= DATE(NOW())")
        )
    );

No need of ? like you tried. With ? you params will be escaped and it won't work with an expression. Only with params, like a PHP datetime or something like this.

Tested with 2.4.2