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.
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();
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.
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);
}
You can't but a simple read is fastest
$last = $this->Model->read(null,$this->Model->id);
精彩评论