3

I want to update multiple rows of a specific model at once, so I have bellow code and data structure. Whenever I tried to update the record every time record gets inserted instead of update.

in my controller

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
}

Here is the data in the different array,

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
        )
bikash.bilz
  • 821
  • 1
  • 13
  • 33
  • 2
    `$products` should be an array of entities... also `debug($productPatch)` to check for possible problems. – ndm Sep 19 '17 at 14:09
  • 1
    Forgot to mention that $products is an array of entities, only better visuality and data format I have printed the code by converting into an array. @ndm – bikash.bilz Sep 19 '17 at 14:12
  • To guide me better, When I print $products I found id index in each array but after patchEntities, I didn't found id in the arrays, I know this is the problem but can't understand what causing this problem :( @ndm – bikash.bilz Sep 19 '17 at 14:14
  • 2
    There could be many reasons, without seeing the full picture I can only shoot in the dark, which isn't overly helpful. You'll have to do some debugging, maybe the data is modified before patching (`beforeMarshal`), maybe you have some custom entity or table (finder) logic that causes this, maybe you are debugging after saving and things go wrong in the saving stage, like application rules, `beforeSave` handlers, etc... it may help if you'd show your debugging results. – ndm Sep 19 '17 at 19:52

1 Answers1

1

You can use updateAll() method to update data in Bulk :

$this->modelClass->updateAll(
    ['published' => true], // fields
    ['published' => false]); // conditions
amar9312
  • 395
  • 2
  • 6
  • 16