Category: Models & ORM

Q: Saving multiple records and get the last inserted Id in ORM

I'm thinking about saving multiple records at once and then get the last Id in cakephp.

From the cake doc (saving data at a time), I know that if you are saving one record:

use Cake\ORM\TableRegistry;

$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->newEntity();

$article->title = 'A New Article';
$article->body = 'This is the body of the article';

if ($articlesTable->save($article)) {
    // The $article entity contains the id now
    $id = $article->id;
}

And for Converting Multiple Records:

$articles = TableRegistry::get('Articles');
$entities = $articles->newEntities($this->request->data());

//then save entity one by one
foreach ($entities as $entity) {

    // Save entity
    $articles->save($entity);
}

But my questions are:

  1. Is there a saveAll() function?
  2. In this case, how to get the last inserted Id?

Please advice.

orm
1 Answers

Version: 3

user
RJ

4

This is okay for last id:

$articles = TableRegistry::get('Articles');
$entities = $articles->newEntities($this->request->data());

//then save entity one by one
foreach ($entities as $entity) {

    // Save entity
    $articles->save($entity);
}

//this is the last id
$id = $articles->id;
RJ
RJ

4

Created: 13 Oct '16

Last Reply: 21 Oct '16

Replies: 1

Views: 1444

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions