David Weng David Weng - 6 months ago 69
PHP Question

CakePHP - How to update multiple records

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

I retrieve multiple records using

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?


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));