开发者

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开发者_Go百科 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜