2011-05-04 98 views
7

如何更新CakePHP中多個記錄的單個字段?CakePHP - 如何更新多個記錄

我使用$this->Item->find('all')檢索多個記錄,我需要爲它們中的每一個設置不同的值並保存。我做

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

,但它提出了一個錯誤,說

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

我在做什麼錯?

回答

9

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

試試這個

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

參見[@ hugofcampos的答案](http://stackoverflow.com/a/18255526/216084)性能。 – 2014-09-04 05:59:04

+0

隨着[Model :: saveMany]的推出(http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-數組)在CakePHP 2.0中,請參閱@ hugofcampos的答案,以獲得更好的方法。 – 2014-10-13 03:38:31

+0

@HamidNazari我認爲這不會很好,如果有數千個字段不推薦 – 2016-04-21 15:04:28

2

你做錯了什麼是$item不是一個對象(也不是items順便說一句),所以你不能調用任何方法。 $items只是一個數組,其中包含您的find()操作的所有結果。

您需要做的是使用saveAll()方法,並在此情況下將其用於適當的對象$this->Item

欲瞭解更多信息,請參閱本頁底部the documentation

18

我要說的是,你應該使用CakePHP Save Many以提高性能。

例:

$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)); 
+0

我們如何在CakePHP 3中使用saveMany? – 2016-04-21 15:08:23