CakePHP not setting the $this->Model->id variable
I am currently trying to access the data that was just inserted using:
if($this->User->save($this->data))
{
$user_id = $this->User->id; #119
...
But I get the error:
Notice (8): Undefined index: id [APP/controllers/users_controller.php, line 119]
Code | Context
if($this->User->save($this->data))
{
$user_id = $this->data['User']['id'];
I don't understand why the save succeeds, but the id is 开发者_如何学运维not set?
EDIT:
So the problem was that because I was using database relations that forced my read to return data from multiple tables, it ended up returning data from multiple tables, so what I really had to do was:$user = $this->User->read();
$id = $user['User']['id'];
rather than:
$user = $this->User->read();
$id = $user['id'];
To get the ID of the last record this model inserted,you should use
$this->User->getLastInsertID();
Usually $this->User->id
is used to make some action know which record it should handle,you cannot use it to retrieve data from database.
Yes, $model->data['Model']['id']
is not updated when saving data. Only $model->id
is. That's all there is to it.
精彩评论