2017-09-19 49 views
3

我想一次更新一個特定模型的多行,所以我有波紋管代碼和數據結構。每當我嘗試更新記錄時,每次插入記錄而不是更新。如何更新模型的多行?

在我的控制器

function products($cat_id = null){ 
    $products = $this->Products->find()->where(['category_id' => $cat_id]); 

    $productPatch = $this->Products->patchEntities($products, $this->request->data); 

    $this->Products->saveMany($productPatch);  //Always creates new record 
} 

這裏

是不同陣列中的數據,

In $products 
    [0] => Array 
     (
      [id] => 13    //product_id 
      [category_id] => 17 
      [slug] => onScreen 
      [status_id] => 1 
     ) 

    [1] => Array 
     (
      [id] => 14 
      [category_id] => 17 
      [slug] => pdf 
      [status_id] => 1 
     ) 

In $this->request->data 


    [0] => Array 
    (
     [id] => 13    //product_id 
     [category_id] => 17 
     [slug] => onScreen 
     [status_id] => 2   //Data changes here 
    ) 

    [1] => Array 
     (
      [id] => 14 
      [category_id] => 17 
      [slug] => pdf 
      [status_id] => 2   //Data changes here 
     ) 
+2

' $ products'應該是一個實體數組......也是'debug($ productPatch)'來檢查可能的問題。 – ndm

+1

忘了提及$ products是一個實體數組,只有更好的可視性和數據格式,我通過轉換成數組來打印代碼。 @ndm –

+0

爲了更好地指導我,當我打印$ products時,我在每個數組中找到了id索引,但在patchEntities之後,我沒有在數組中找到id,我知道這是問題,但無法理解導致此問題的原因: (@ndm –

回答

1

可以使用updateAll()方法在批量更新數據:

$this->modelClass->updateAll(
    ['published' => true], // fields 
    ['published' => false]); // conditions