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?
CakePHP - Update a Record. To update a record in database we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update.
To update a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get () method. The get () method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update.
The Validating Data chapter has more information on how to use the validation features of CakePHP to ensure your data stays correct and consistent. When creating or merging entities from request data you need to be careful of what you allow your users to change or add in the entities.
As you can see, the comment with id 2 is no longer there, as it could not be matched to anything in the $newData array. This happens because CakePHP is reflecting the new state described in the request data. Some additional advantages of this approach is that it reduces the number of operations to be executed when persisting the entity again.
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));
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With