简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM