12

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.

3
  • Can you clarify, I don't really understand what you're asking.
    – Brian
    Commented Mar 22, 2011 at 4:30
  • 1
    i want get data like $last in above example that don't need to select database. Commented Mar 22, 2011 at 4:33
  • Please review again this questions and answers. I have the feeling it is still not clear. And also as it's some time ago, did you solve it in the meantime your own or what was your solution / alternative?
    – hakre
    Commented Dec 28, 2012 at 11:36

4 Answers 4

15

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();
1
  • Welcome to Stack Overflow! Thanks for posting your answer! Please be sure to read the FAQ on Self-Promotion carefully. Also note that it is required that you post a disclaimer every time you link to your own site/product. Commented Dec 26, 2012 at 11:10
12

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.

1
  • Most explanatory answer!
    – paul.ago
    Commented May 13, 2012 at 14:25
5

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);
}
0

You can't but a simple read is fastest

  $last = $this->Model->read(null,$this->Model->id);

Not the answer you're looking for? Browse other questions tagged or ask your own question.