Duplicate entities into another model - newEntities just returns empty []

I am trying to copy some entities from 1 table to another and keep coming up with an empty arrays - it’s when I try and create newEntities does it stop working…

    $this->loadModel('Originals');
    $this->loadModel('Duplicates');

    $toCopy = $this->Originals->find('all')
    ])->toArray();

    $data = $this->Duplicates->newEntities($toCopy, ['checkExisting' => false]); 
    // $data = [];
    $result = $this->Duplicates->saveMany($data, ['checkExisting' => false]);
    debug($result);
    // $result = []
    exit;

I am really struggling to see what’s missing - the only thing I can see is that the $entities in $toCopy are of type Original and not Duplicate - do you need to somehow convert the entity?

Also the repository is Original as well.

This seems like it should be simple but I don’t know what else to look for and empty []s are no good for debugging!

Thanks

newEntities() wants an array of array data.

So, you need to loop through the array of entity objects ($toCopy) and run toArray() on each one to convert it from an entity object to an array.

Then I think newEntities() will accept it.

1 Like