Insert and update bulk data in CakePHP 3.7

Author - Kailash Kumar

How to Insert and update bulk data in CakePHP 3.7?

We can insert and update multiple records using “saveMany($entities)” function. We can create entities array from “newEntities() / patchEntities()” functions. newEntities function is used to insert new data and patchEntities function is used to update existing data. The only difference between insert and update is that how we create entities array. Below is an example of update and insert operations.

For Insert:

$data = [
    [
        'name' => 'test',
        'email' => ‘test@mail.com’
    ],
    [
        'name' => 'test2',
        'email' => ‘test2@mail.com’
    ]
];

$users = TableRegistry::getTableLocator()->get('Users');
$entities = $users->newEntities($data);
$result = $users->saveMany($entities);

For Update:

$data = [
    [
        ‘id’ => 100, // primary key required for update
        'name' => 'test',
        'email' => ‘test@mail.com’
    ],
    [
        ‘id’ => 101, // primary key required for update
        'name' => 'test2',
        'email' => ‘test2@mail.com’
    ]
];

$users = TableRegistry::getTableLocator()->get('Users');
$entities = $users->patchEntities($data);
$result = $users->saveMany($entities);
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *