在 CakePHP 的 updateAll() 方法中使用 IN 子句 3.x

Use IN clause in updateAll() method in CakePHP 3.x

我正在使用 Cakephp 3.x,我想为多个 ID 更新我的单个字段。像这样的..

UPDATE mytable SET `status` = '1' WHERE ID IN (1,2,3)

目前我正在使用查询通过 cakpehp 执行此操作

$this->Leaveregisters->query()
                ->update()
                ->set(['leaveregister_status' => $this->request->data('status')])
                ->where(['leaveregister_id IN ('.$this->request->data('final_ids_string').')'])
                ->execute();  

好吧,这对我有用,但我希望使用 cakephp 3.xs 的 ORM 方法来执行此操作..所以我正在尝试使用它

$table->updateAll(['field' => $newValue], ['id' => $entityId]);

但此代码仅适用于我不想要的单个 ID。我也不想使用 foeach 循环来执行相同的操作。相反,我希望在任何情况下都通过数组或逗号分隔的 ID 传递,并希望执行相同的操作。

有什么方法可以使用 ORM 方法使用 cakephp 3.x

执行相同的操作

谢谢

您必须使用数组数据类型来传入 IN CLAUSE

$in_condition= explode(",",$this->request->data('final_ids_string'));

$this->Leaveregisters->query()
                ->update()
                ->set(['leaveregister_status' => $this->request->data('status')])
                ->where(['leaveregister_id IN' => $in_condition])
                ->execute(); 

使用模型的 updateAll()

$table->updateAll(array(
       // new values
    ),
    array('id' => array(1,2,3,4,5,6))
);

使用 updateAllquery() 对象进行批量更新与您在 this

末尾的手册中阅读的内容相同

所以你可以做到

$this->Leaveregisters->query()
    ->update()
    ->set(['leaveregister_status' => $this->request->data('status')])
    ->where(['leaveregister_id IN' => [1,2,3])
    ->execute(); 

$this->Leaveregisters->updateAll(
    ['leaveregister_status' => $this->request->data('status')]
    ['leaveregister_id IN' => [1,2,3]);

请记住,当使用 IN 子句时,您必须传递一个数组。阅读手册中关于如何创建 IN 子句的 this 部分