0

CakePHP 3.6.14

此代码重现错误的数字:

        $where = [
            'Postings.source' => $source,
            'Postings.approved' => 1,
            'Postings.deleted' => 0,
            'Postings.disabled' => 0
        ];

        if ($source !== null) {
            $where['Postings.created >='] = '(NOW() - INTERVAL 3 DAY)';
        }
        $count = $this->Postings
            ->find()
            ->where($where)
            ->count();
        debug($count); exit;

       // 77568 total of all records
########## DEBUG ##########
[
    'Postings.source' => 'xzy',
    'Postings.approved' => (int) 1,
    'Postings.deleted' => (int) 0,
    'Postings.disabled' => (int) 0,
    'Postings.created >=' => '(NOW() - INTERVAL 3 DAY)'
]

//SQL produced by this query:

SELECT (COUNT(*)) AS `count` 
FROM postings Postings 
WHERE (
   Postings.source = 'xzy' 
   AND Postings.approved = 1 
   AND Postings.deleted = 0 
   AND Postings.disabled = 0 
   AND Postings.created >= '(NOW() - INTERVAL 3 DAY)' // <<<< with quotes
)

但是原始的sql查询:

SELECT COUNT(*) as `count
FROM `postings` 
WHERE `source` = 'xzy' 
AND `approved` = 1 
AND `deleted` = 0 
AND `disabled` = 0 
AND `created` >= (NOW() - INTERVAL 3 DAY) // <<< without quotes
// return correct num 2119

怎么修?

4

2 回答 2

2

条件右侧的值key => value始终受到绑定/强制转换/转义,除非它是表达式对象。查看生成的查询,您的 SQL 片段最终将成为字符串文字,即:

created >= '(NOW() - INTERVAL 3 DAY)'

长话短说,使用一个表达式,或者一个原始的:

$where['Postings.created >='] = $this->Postings->query()->newExpr('NOW() - INTERVAL 3 DAY');

或使用函数生成器:

$builder = $this->Postings->query()->func();
$where['Postings.created >='] = $builder->dateAdd($builder->now(), -3, 'DAY');

也可以看看

于 2019-01-14T22:51:00.810 回答
0

您应该使用查询生成器并添加到select方法count功能。

一切都在这里描述:https ://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions

于 2019-01-14T22:38:05.850 回答