CakePHP 3.6 - 查找在两个日期之间创建的所有记录

CakePHP 3.6 - Find All Records Created Between Two Dates

我要查找两个日期之间的所有记录

我的变量

 $start = '01/01/2009';
 $end = '07/24/2019';

我试过了

$gross = $this->CartOrders->find('all')->where(['placed >=' => $start])->andWhere(['placed <=' => $end])->all();

上面的查询片段

... FROM cart_orders CartOrders 
WHERE (placed >= :c0 AND placed <= :c1) 
[params] => Array ( 
     [:c0] => Array ( [value] => 01/01/2009 [type] => datetime [placeholder] => c0 ) 
     [:c1] => Array ( [value] => 07/24/2019 [type] => datetime [placeholder] => c1 ) )

结果

 Cake\ORM\ResultSet Object ( [items] => Array ( ) )

我也试过了

$gross = $this->CartOrders->find('all')->where(function($exp) use($start,$end) {
        $exp->lte('placed', $end);
        $exp->gte('placed', $start);
        return $exp;
    })->all();

我也试过了

$gross = $this->CartOrders->find('all')->where(function($q) use($start,$end) {
        return $q->between('CartOrders.placed', $start, $end, 'date');
    })->all();

关于如何实现这个的任何想法?

尝试使用

$this->CartOrders->find('all', array('conditions' => array(
        'date(placed) BETWEEN "'.$start.'" AND "'.$end.'"')));

这是一个非正统的解决方案,但它对我来说适用于多种情况

$this->set('gross',$this->CartOrders-> find(
                'all', array(
                    'conditions' => array(
                        'CartOrders.placed >=' => $start,
                        'CartOrders.placed <=' => $end
                    ))
            ));  // here gross is a variable to store the data from DB and CartOders is the Model name

使用QueryExpression

use Cake\Database\Expression\QueryExpression;

$query = $this->CartOrders->find()
->where(function (QueryExpression $exp, Query $q) use ($start,$end){
    return $exp->between('placed', $start, $end);
});

如果用户试图在同一天搜索,可能会添加一个时间条件

return $exp->between('placed', $start . " 00:00:00", $end . " 23:59:59");

原来是日期格式问题。

以下解决了我的问题。

$start = '01/01/2009';
$end = '07/24/2019';

$start = DateTime::createFromFormat('d/m/Y', $start);
$end = DateTime::createFromFormat('d/m/Y', $end);

$gross = $this->CartOrders->find('all')->where([
     'placed >=' => $start->format('Y-m-d')
])->andWhere([
     'placed <=' => $end->format('Y-m-d')
])->all();

这 link 有帮助

PHP convert date format dd/mm/yyyy => yyyy-mm-dd