php - CakePHP 3 - 多条件查找

标签 php cakephp cakephp-3.0

我正在尝试进行查询以查找具有特定集合或 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())
    ]);

关于php - CakePHP 3 - 多条件查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856251/

相关文章:

php - Ajax php 在 mysql 中插入一些奇怪的 jquery 代码而不是问号

php - 一个 View (网页)中来自多个模型的数据

javascript - 从嵌套 JSON 检索数据到 Morris.js xkey

php - cakephp 3 在记录时使用范围

mysql - 如何使用cakephp检索最后一组数据

php - Cakephp 3.0.3 如何使用默认布局?

testing - CakePHP3 : Mock methods in integration tests?

php - 从 Guzzle 中捕获异常

PHP 向 Amazon SES 发送大量电子邮件

php - 如何从 Survey Monkey 调查中获取受访者 ID?