Getting pasted identifiers from saveAll () in CakePHP

Using saveAll() to save multiple entries in CakePHP, I can successfully save them in a table. But the problem occurs when retrieving the identifiers of these stored rows. LastInsertID() returns here only one last identifier. How can I get all the last inserted identifiers that I inserted using saveAll() ?

+6
source share
1 answer

the afterSave function is called after each separate save in the saveAll execution, so you can: In the AppModel

 class AppModel extends Model { var $inserted_ids = array(); function afterSave($created) { if($created) { $this->inserted_ids[] = $this->getInsertID(); } return true; } } 

You can put this code in any model, and it should work fine. Then, to return the identifiers after saving to the controller, you will do this:

 if($this->Post->saveAll($posts)) { $post_ids=$this->Post->inserted_ids; //contains insert_ids } 

Hope this helps

+23
source

Source: https://habr.com/ru/post/911090/


All Articles