shabby
shabby

Reputation: 3222

CakePHP How to get latest auto incremented id after saving data

I have checked this question as well and this one as well. I am trying to implement the model described in this question.

What I want to do is, on the add function of message controller, create a record in thread table(this table only has 1 field which is primary key and auto increment), then take its id and insert it in the message table along with the user id which i already have, and then save it in message_read_state and thread_participant table.

This is what I am trying to do in Thread Model:

function saveThreadAndGetId(){
    //$data= array('Thread' => array());
    $data= array('id' => ' ');
   //Debugger::dump(print_r($data));
   $this->save($data);
   debug('id: '.$this->id);
    $threadId = $this->getInsertID();
    debug($threadId);
    $threadId = $this->getLastInsertId();
    debug($threadId);
    die();
    return $threadId;
}


$data= array('id' => ' ');

This line from the above function adds a row in the thread table, but i am unable to retrieve the id. Is there any way I can get the id, or am I saving it wrongly?

Initially I was doing the query thing in the message controller:

$this->Thread->query('INSERT INTO threads VALUES();');

but then i found out that lastId function doesnt work on manual queries so i reverted.

Upvotes: 0

Views: 1499

Answers (2)

Igor L.
Igor L.

Reputation: 3465

This here returns the next auto increment value.

/* @return int */
private function getNextThreadId() {
    $result = $this->Thread->query("SHOW TABLE STATUS LIKE 'threads';");
    $next = $result[0]['TABLES']['Auto_increment'];
    return $next;
}

Thread -> or any other name of your model

Threads -> or any other name of your db table

Upvotes: 0

Dave
Dave

Reputation: 29131

You're setting $data to basically an empty array with an id of ' '. Not sure what you were expecting out of that. :) Try NOT manually setting the 'id' to an empty string, and saving some data. Then you should get the ID just fine.

Upvotes: 1

Related Questions