CakePHP 3.5查询构建器返回空结果,MySQL执行生成SQL却有数据
解决CakePHP查询返回空但原生SQL能查到数据的问题
我一眼就看出问题出在你写的日期条件上!CakePHP的查询构建器对字符串值会自动做参数化处理,这就导致你写的'CURDATE()-INTERVAL 7 DAY'被当成了普通字符串,而不是SQL表达式。最终生成的SQL里这部分会带上引号,变成这样:
DATE(Vehicles.second_enlisting_date) <= 'CURDATE()-INTERVAL 7 DAY'
这种字符串和日期的比较自然不会返回任何结果,但你手动在MySQL控制台执行的时候没有引号,所以能正确计算日期区间。
给你几种可行的修复方案:
方案1:直接使用SQL片段字符串
最简单的方式就是把整个条件写成SQL片段字符串,这样CakePHP不会对它做参数化处理:
$query = $this->Vehicles->find() ->where([ 'Vehicles.first_enlisting_date IS NOT NULL', 'Vehicles.second_enlisting_date IS NOT NULL', 'Vehicles.third_enlisting_date IS NULL', 'DATE(Vehicles.second_enlisting_date) <= CURDATE() - INTERVAL 7 DAY' ]);
方案2:使用QueryExpression构建表达式
如果你更倾向于用CakePHP的表达式语法,也可以用newExpr()来构建比较条件:
$query = $this->Vehicles->find() ->where([ 'Vehicles.first_enlisting_date IS NOT' => null, 'Vehicles.second_enlisting_date IS NOT' => null, 'Vehicles.third_enlisting_date IS' => null, $this->Vehicles->query()->newExpr()->lte( 'DATE(Vehicles.second_enlisting_date)', 'CURDATE() - INTERVAL 7 DAY' ) ]);
方案3:用func()生成SQL函数表达式
这种方式更符合CakePHP的ORM风格,通过func()来生成CURDATE()相关的表达式:
$query = $this->Vehicles->find() ->where([ 'Vehicles.first_enlisting_date IS NOT' => null, 'Vehicles.second_enlisting_date IS NOT' => null, 'Vehicles.third_enlisting_date IS' => null, 'DATE(Vehicles.second_enlisting_date) <=' => $this->Vehicles->query()->func()->curdate()->sub('INTERVAL 7 DAY') ]);
随便选一种方案试一下,应该就能得到和原生SQL一致的查询结果了!
内容的提问来源于stack exchange,提问作者Mushfiqur Rahman
相关产品推荐
相关产品推荐

