Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving inserted IDs from saveAll() in CakePHP

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()?

like image 370
Vineet Avatar asked Mar 19 '12 11:03

Vineet


1 Answers

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

like image 182
Sudhir Bastakoti Avatar answered Oct 08 '22 03:10

Sudhir Bastakoti