CakePHP 3 - 查找多个条件

时间:2017-12-17 14:47:23

标签: 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'
    ]
]

提前致谢。

2 个答案:

答案 0 :(得分:1)

您正在寻找的内容称为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())
    ]);

答案 1 :(得分:0)

看看Cake 3的查询生成器: Case statements

您可以执行以下操作:

   $devIds = [1,2,3];
   $revenuesQuery = $this->revenues->find()
            ->where(function (QueryExpression $exp) use ($devIds) {
                return $exp
                        ->in('device_id', $devIds)
                        ->eq('date', q->func()->now() );
            });