Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get model data after save ( CakePHP ) [closed]

Tags:

cakephp

I want to get the latest data from the model after it has saved without doing another select.

Currently I do this:

if ($this->Model->save($data)){
    $last = $this->Model->find('first',array(
        'conditions' => array('Model.id' => $this->Model->id)
    );
    $last['Model']['dataChangedByBehaviors']; // <-- data I want
}

I want to get any data that was set in model callbacks or behaviors without performing an extra find.

like image 355
meotimdihia Avatar asked Mar 22 '11 04:03

meotimdihia


3 Answers

There are two different situations for your example:

  • $data holds a complete record of your model data. Then you can simply access $data['Model']['dataChangeByBehaviors']:
if ($this->Model->save($data)){
      $data['Model']['dataChangeByBehaviors'];  //---- I want get this
}

So, here the answer is: You already have the data.

(Note: If it's a new record, $data will of course not contain the ID, which you need to get from $this->Model->id. And if you are making any changes in the beforeSave() callback, these will of course not be reflected in your $data).

  • $data only contains certain fields that you update in a record. Then there is no other way to get the complete record, apart from reading it from the database - which is what you are doing already and can be simplified as suggested by Leo:
if ($this->Model->save($data)){
      $last = $this->Model->read(null,$this->Model->id);
      $last['Model']['dataChangeByBehaviors'];  //---- I want get this
}

So here the answer is: There is no way of getting the data without a database request.

like image 86
pixelistik Avatar answered Nov 07 '22 18:11

pixelistik


I'm not understand why people doing labor work. Just use getLastInsertId() CakePHP's inbuilt function and it's done :

$post_id=$this->Post->getLastInsertId();
like image 23
Hardik Sondagar Avatar answered Nov 07 '22 17:11

Hardik Sondagar


If you're looking for some solution like if ($last = $this->Model->save($data)), I think there's no such thing as that.

But you can save some code using findById:

if ($this->Model->save($data)){
      $last = $this->Model->findById($this->Model->id);
}
like image 5
Min Avatar answered Nov 07 '22 19:11

Min