سؤال

I have two models, donors hasMany donations.

Upon creation of donor record, I want to update some donor fields. I tried using saveAssociated() as follows

$this->Donation->create();
$this->request->data['Donation']['donor_id'] = $id;
$this->request->data['Donor']['last_donated'] = date('Ymd H:i:s', strtotime('now'));            

if($this->Donation->saveAssociated($this->request->data , array('deep' => true))){
}

Everything works except that the donor is not updated but a new donor record is created altogether.
Do I need to set the donor id manually somehow?

هل كانت مفيدة؟

المحلول

"Do I need to set the donor id manually somehow ?"

Yes.

More explanation:

In cake, if you want to update something, you need to pass the id, otherwise you'll create a new record. You can also "load" the model instance like

$this->Model->id = $id;

and then the save will update the row with that id. But I always find it more mentally-safe to add the id to the saved array, specially when using saveAll, saveMany and saveAssociated.

In your case, you must have the donor's id somewhere, cake is not that magical and it won't know what donor you are refering to.

Something like this

$this->request->data['Donor']['id'] = $the_id;

will do the trick.

... or you can save the donor's last_donated time with a different query, if it's giving you too much trouble.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top