CakePHP 3 - 查找多个条件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CakePHP 3 - 查找多个条件相关的知识,希望对你有一定的参考价值。
我正在尝试进行查询以查找具有特定集或ID的所有行。
例如,我想找到一个具有以下值之一的device_id字段:1 3 5
我尝试将其添加为数组,但我收到一条错误消息:无法将值转换为整数
这是我的代码:
$revenuesQuery = $revenues->find('all', [
'conditions' => [
'device_id' => [1, 3, 5],
'date' => date('Y-m-d')
]
]);
如您所见,device_id是一个整数数组(3和4),我不想拥有其中一个(3或4)的行。如果我将代码更改为不使用数组而是使用这样的硬整数:
$revenuesQuery = $revenues->find('all', [
'conditions' => [
'device_id' => 3,
'date' => date('Y-m-d')
]
]);
它工作得很好?
这是我的调试查询:
'(help)' => 'This is a Query object, to get the results execute or iterate it.',
'sql' => 'SELECT Revenues.id AS `Revenues__id`, Revenues.device_id AS `Revenues__device_id`, Revenues.revenue AS `Revenues__revenue`, Revenues.date AS `Revenues__date` FROM revenues Revenues WHERE (device_id = :c0 AND date = :c1)',
'params' => [
':c0' => [
'value' => [
(int) 0 => (int) 3,
(int) 1 => (int) 4
],
'type' => 'integer',
'placeholder' => 'c0'
],
':c1' => [
'value' => '2017-12-17',
'type' => 'date',
'placeholder' => 'c1'
]
]
提前致谢。
答案
您正在寻找的是IN operator。
将单词IN
添加到字段名称的末尾。
$revenuesQuery = $revenues->find('all', [
'conditions' => [
'device_id IN' => [1, 3, 5],
'date' => date('Y-m-d')
]
]);
或者,查询表达式构建器更详细,是我在Cakephp中创建查询的首选方法。
$q = $revenues->query();
$revenuesQuery = $revenues->find('all')
->where([
$q->newExp()->in('device_id', [1, 3, 5]),
$q->newExp()->eq('date', $q->func()->now())
]);
以上是关于CakePHP 3 - 查找多个条件的主要内容,如果未能解决你的问题,请参考以下文章