0

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.

Community
  • 1
  • 1
shabby
  • 3,002
  • 3
  • 39
  • 59

2 Answers2

1

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.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • what data i must save? the table only has a single id, autoincrement column, i have tried all other options, this way it savs, but doent show up the last inserted id... – shabby Nov 02 '12 at 06:21
  • I think the bigger question is, why do you have a table with a single column that stores no actual data? – Dave Nov 02 '12 at 13:19
  • I was just implementing the schema in the referred question, I have fixed it and its working now, but im wondering how to save it if somehow a table has one column/field – shabby Nov 02 '12 at 13:52
  • Try just doing $this->save(); or $this->save(array('Thread')); – Dave Nov 02 '12 at 14:03
0

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

Igor L.
  • 3,159
  • 7
  • 40
  • 61