'CakePHP 3 - how to patchEntities where form data is collected within a foreach

My scenario is similar to this post here: CakePHP 3 - Form data format for patchEntities() However, I am trying to update multiple entries that are represented within a foreach.

The Form looks like this:

<?= $this->Form->create(null, ['url' => ['controller' => 'Products', 'action' => 'index']]); ?>
  <?php foreach ($products as $key => $product): ?>
    <?= $this->Form->hidden("{$key}.id", ['value' => $product->id]); ?>
    <?= $this->Form->control("{$key}.reduced_price", ['value' => $product->reduced_price]); ?>
    <?= $this->Form->control("{$key}.price", ['value' => $product->price]); ?>
  <?php endforeach; ?>
<?= $this->Form->end(); ?>

Output of $this->getRequest()->getData()

 0 => array:3 [▼
    "id" => "7319"
    "reduced_price" => "987"
    "price" => "200"
 ]
 1 => array:3 [▼
    "id" => "7318"
    "reduced_price" => "875785"
    "price" => "299.5"
 ]

Controller Action:

if ($this->getRequest()->is('post')) {
  $products = $this->Products->find()->toArray();
  $entities = $this->Products->patchEntities($products, $this->getRequest()->getData());
  $this->Products->saveMany($entities);
}

If I follow ndm's advice then the entries would have to be updated, but they won't. But why?

Update: If i use save() inside a foreach the records are being saved

$products = $this->Products->find()->toList();
$entities = $this->Products->patchEntities($products, $this->request->getData());

foreach ($entities as $entity) {
  $this->Products->save($entity);
}

But why does saveMany not work for me?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source