dongxie8856
2017-12-17 14:47 阅读 38
已采纳

CakePHP 3 - 查找多个条件

I am trying to make a query to find all rows with a certain set or ID's.

For instance I wanna find all with a device_id field that has one of the following values: 1 3 5

I tried adding it as an array, but I get an error saying: Cannot convert value to integer

Here is my code:

$revenuesQuery = $revenues->find('all', [
        'conditions' => [
            'device_id' => [1, 3, 5],
            'date' => date('Y-m-d')
        ]
    ]);

As you see, the device_id is an array of integers (3 and 4) and I wan't rows that has one of these (either a 3 or a 4). If I change the code to not use an array but a hard integer like this:

$revenuesQuery = $revenues->find('all', [
        'conditions' => [
            'device_id' => 3,
            'date' => date('Y-m-d')
        ]
    ]);

It works just fine?

Here is my query as debugged:

'(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'
    ]
]

Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dsa1234569 dsa1234569 2017-12-17 16:33

    What you're looking for is called the IN operator.

    Add the word IN to the end of the field name.

    $revenuesQuery = $revenues->find('all', [
        'conditions' => [
            'device_id IN' => [1, 3, 5],
            'date' => date('Y-m-d')
        ]
    ]);
    

    Alternatively the query expression builder is more verbose, and my preferred way of creating queries in CakePHP.

    $q = $revenues->query();
    $revenuesQuery = $revenues->find('all')
        ->where([
            $q->newExp()->in('device_id', [1, 3, 5]),
            $q->newExp()->eq('date', $q->func()->now())
        ]);
    
    点赞 评论 复制链接分享

相关推荐