Home » Php » php – CakePHP – How to update multiple records

php – CakePHP – How to update multiple records

Posted by: admin July 12, 2020 Leave a comment

Questions:

How can I update a single field of multiple records in CakePHP?

I retrieve multiple records using $this->Item->find('all') and I need to set different values for each of them and save. I do

$items = $this->Item->find('all', array(
    'fields' => array('Item.id', 'Item.order'),
    'conditions'=> array(
        'Item.project_id =' => $this->request->params['project_id'],
    ),
    'order' => array ('Item.order ASC')
));

foreach($items as $key => $item) {
    $item->saveField('Item.order', rand(1, 10));
}

but it raises an error saying

Fatal error: Call to a member function saveField() on a non-object

What am I doing wrong?

How to&Answers:

Update: Please note that this is an old answer meant for CakePHP 1.3. For a modern approach please refer to the answer below.

Try this

foreach($items as $key => $item) {
    $this->Item->id = $item['Item']['id'];
    $this->Item->saveField('order', rand(1, 10));
}

Answer:

I would say that you should use CakePHP Save Many to improve the performance.

Ex:

$data = array(
    array( 'Item' => array('id' => 2, 'order' => rand(1,5)) ),
    array( 'Item' => array('id' => 3, 'order' => rand(1,5)) ),
);
$Model->saveMany($data, array('deep' => true));

Answer:

What you’re doing wrong is that $item is not an Object (nor is items btw), so you cannot call any methods on this. $items is just an array with all the results from your find() operation.

What you need to do is use the saveAll() method and use it on a proper object, $this->Item in this case.

See the bottom part of this page from the documentation for more info.