cakephp 3.x saving multiple entities - newEntities

谁说我不能喝 提交于 2019-12-04 10:04:41

Did you somewhere saw this Table.index.field style being used, or did you just tried something and hoped it would work?

When saving many records respectively creating many entities, the expected format is a numerically indexed array that holds the data for the individual records, just as shown in the docs

Cookbook > Database Access & ORM > Saving Data > Converting Multiple Records

When creating forms that create/update multiple records at once you can use newEntities():

[...]

In this situation, the request data for multiple articles should look like:

$data = [
    [
        'title' => 'First post',
        'published' => 1
    ],
    [
        'title' => 'Second post',
        'published' => 1
    ],
];

So your inputs should not use the table name, but just the index and the field name, like

echo $this->Form->input('0.transaction_id', /* ... */);
echo $this->Form->input('0.amount', /* ... */);
echo $this->Form->input('0.account_id', /* ... */);
echo $this->Form->input('1.transaction_id', /* ... */);
echo $this->Form->input('1.amount', /* ... */);
echo $this->Form->input('1.account_id', /* ... */);
echo $this->Form->input('2.transaction_id', /* ... */);
echo $this->Form->input('2.amount', /* ... */);
echo $this->Form->input('3.account_id', /* ... */);
Rana

Try this:

$splits = TableRegistry::get('splits'); 

$entities = $splits->newEntities($this->request->data());

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

Try this example to insert multiple recored in cakphp 3.x

$passwords = $this->request->data('password_id');
foreach ($passwords as $password) {
$data = [
    'event_id'    => $this->request->data('event_id'),
    'password_id' => $password
];
$eventPasswordAll = $this->EventPasswordAll->newEntity();
$this->EventPasswordAll->patchEntity($eventPasswordAll, $data);
$this->EventPasswordAll->save($eventPasswordAll );}

I hope it is useful to your question

please reviwe it, Thanks !

Temístocles Arêa

If you’d like to process all the entities as a single transaction you can use transactional():

Although using a loop, "transations" avoids errors if the "save" does not work.

    // In a controller.
    $articles->getConnection()->transactional(function () use ($articles, $entities) {
        foreach ($entities as $entity) {
            $articles->save($entity, ['atomic' => false]);
        }
    });

Converting Multiple Records - CakePHP 3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!