Using saveAll()
to save multiple records in CakePHP, I am able to save them successfully in a table. But the problem arises while retrieving the IDs of those saved rows. LastInsertID()
returns only a single last ID here. How can I get all the last inserted IDs which I have inserted using saveAll()
?
Asked
Active
Viewed 7,063 times
8
1 Answers
27
afterSave function is called after each individual save in a saveAll execution, so you could do: In your AppModel
class AppModel extends Model {
var $inserted_ids = array();
function afterSave($created) {
if($created) {
$this->inserted_ids[] = $this->getInsertID();
}
return true;
}
}
You can place this code into any model and it should work fine. Then to return the IDs after the saveAll in your controller, you would do so like this:
if($this->Post->saveAll($posts)) {
$post_ids=$this->Post->inserted_ids; //contains insert_ids
}
Hope it helps

Sudhir Bastakoti
- 99,167
- 15
- 158
- 162
-
Thanx Sudhir,i tried this but its throwing an error Undefined property: AppModel:inserted_ids in my controller, what can be the reason..?? – Vineet Mar 19 '12 at 13:10
-
@vin.it remove var before $inseted_ids – Ehtesham Mar 19 '12 at 15:04
-
@ehtesham: thanx ehtesham.i tried it but its still throwing the same error. any other possibilities..? – Vineet Mar 20 '12 at 05:36
-
3It's cool seeing code copied and pasted from one's own blog in a Stack Overflow answer :D – daftv4der Oct 22 '13 at 10:34
-
yes, it should work fine with atomic option set to true. – Sudhir Bastakoti Mar 15 '17 at 09:39