简体   繁体   中英

Cakephp 3 table updateAll using array

In Cakephp 2 's model updateAll, we were using arrays as conditions. But this doesn't work :

$data=array(12, 22, 44);
TableRegistry::get('Foobar')->updateAll(
   array("checked" => 1),
   array("user_id" => $data) 
 );

Is this not possible in Cakephp 3's updateAll ?

This works in cakephp 3:

$data=12;
TableRegistry::get('Foobar')->updateAll(
   array("checked" => 1),
   array("user_id" => $data) 
 );

Regarding to API docs , $conditions defined like this:

updateAll( array $fields , mixed $conditions )

array $fields
A hash of field => new value.

mixed $conditions
Conditions to be used, accepts anything Query::where() can take.

Edit:
In case of cake works well and I'm making a mistake. How can I understand the cause ? Because when condition is an integer, code works well.

Edit2: This also works well:

 $data=array(12, 22, 44);
 ConnectionManager::get('default')->query('UPDATE foobars SET checked=1 
     WHERE user_id IN ('.implode(",",$data).')')->execute();

A little late to the discussion, but since I had a similar problem, using something like id in array condition, this is how is done now on Cakephp 3.

//using the same example
$data=array(12, 22, 44);

TableRegistry::get('Foobar')->updateAll(
   ["checked" => 1],
   ["user_id IN " => $data] //mind the IN on the condition
);

Here is another way from the docs , updated for the example

$articles = TableRegistry::get('Articles');
$data=array(12, 22, 44);

$query = $articles->query();
$query->update()
    ->set(['checked' => true])
    ->where(['user_id IN' => $data])
    ->execute();

Hope it helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM