David Weng
David Weng

Reputation: 4235

CakePHP - How to update multiple records

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?

Upvotes: 7

Views: 14366

Answers (3)

Hamid Nazari
Hamid Nazari

Reputation: 3985

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

Upvotes: 9

hugofcampos
hugofcampos

Reputation: 695

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

Upvotes: 18

vindia
vindia

Reputation: 1678

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.

Upvotes: 2

Related Questions