CakePHP: how to get recently created auto-incremented field
I have a user submit a field to the database, it 开发者_StackOverflowvalidates, and makes the entry. The primary key of this new row is auto-incremented.
The user then gets to another form where that newly created field is required.
Can anyone shed any light on this problem?
Thanks in advance!
Check out Model::getInsertID();
$this->getLastInsertID();
cakephp model docs
// Save the first form
$this->Ingredient->save($newData);
// Get the id of the record just saved
$newIngredientId = $this->Ingredient->id;
// Redirect to a new form
$this->redirect(array(
'controller' => 'dish',
'action' => 'add',
'?' => array('lastId' => $newIngredientId)
));
http://book.cakephp.org/view/1031/Saving-Your-Data, http://book.cakephp.org/view/1442/link
If it's in the database, when you get to your next form just read it out again in your controller and set it to a view variable.
$this->set('lastid', $this->Model->read(null,$id));
Or if you need to search the database for the field use find
$this->set('lastid', $this->Model->find('first', array('conditions'=>array('username'=>'MyUserName')) , array('id')));
You could go around it by using mysql_insert_id()
精彩评论