Cake\ORM\Table::saveMany PHP Method

saveMany() public method

The records will be saved in a transaction which will be rolled back if any one of the records fails to save due to failed validation or database error.
public saveMany ( array | Cake\ORM\ResultSet $entities, array | ArrayAccess $options = [] ) : boolean | array | Cake\ORM\ResultSet
$entities array | Cake\ORM\ResultSet Entities to save.
$options array | ArrayAccess Options used when calling Table::save() for each entity.
return boolean | array | Cake\ORM\ResultSet False on failure, entities list on success.
    public function saveMany($entities, $options = [])
    {
        $isNew = [];
        $return = $this->connection()->transactional(function () use($entities, $options, &$isNew) {
            foreach ($entities as $key => $entity) {
                $isNew[$key] = $entity->isNew();
                if ($this->save($entity, $options) === false) {
                    return false;
                }
            }
        });
        if ($return === false) {
            foreach ($entities as $key => $entity) {
                if (isset($isNew[$key]) && $isNew[$key]) {
                    $entity->unsetProperty($this->primaryKey());
                    $entity->isNew(true);
                }
            }
            return false;
        }
        return $entities;
    }

Usage Example

 public function testFind()
 {
     $entities = [];
     foreach ($this->entityMap as $discriminator => $class) {
         $data = ['discriminator' => $discriminator];
         $entities[] = $this->table->newEntity($data);
     }
     $this->table->saveMany($entities);
     $found = $this->table->find()->toArray();
     $this->assertCount(6, $found);
     foreach ($found as $entity) {
         $class = $this->entityMap[$entity->discriminator];
         $this->assertInstanceOf($class, $entity);
     }
 }