dongxie8856 2017-12-17 14:47
浏览 42
已采纳

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 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())
        ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献