如何更新模型的多行?

时间:2017-09-19 13:47:05

标签: cakephp cakephp-3.0 cakephp-3.2

我想一次更新特定模型的多行,所以我有下面的代码和数据结构。每当我尝试更新记录时,每次插入记录而不是更新。

在我的控制器中

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
        )

1 个答案:

答案 0 :(得分:1)

您可以使用updateAll()方法更新批量数据:

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