I would suggest that you write a special model method for this task,
because the {before|after}Save callbacks can loop quite easily, which can
cause high blood pressure.
Also helpful, if you use the MPTT, you can get ALL the children as a
non-threaded result by using the LEFT and RIGHT fields. Also, if you fiddle
too much with the parent-child and left/right values, make sure to rebuild
the tree structure every now and then.
Here's some imagined code I wrote just now... It's not tested or anything,
but should point you in the right direction.
class MyModel extends AppModel {
public function saveAndUpdateRelatedModel($data) {
if (empty($data[$this->alias]['other_model_id']) &&
!empty($data[$this->alias]['parent_id'])){
// the related model is not set AND has parent
$this->recursive = -1;
$parentRecord = $this->read(null,
$data[$this->alias]['parent_id']);
if (!empty($parentRecord[$this->alias]['other_model_id'])){
// copy the other_model_id from the parent
$data[$this->alias]['other_model_id'] =
$parentRecord[$this->alias]['other_model_id'];
}
}
//save the record with other model relation
$saved = $this->save($data);
//now pass it on to children
$children = $this->find('all', array(
// I have not idea if this is done right, check the docs and test...
'conditions' => array(
'left >' => $saved[$this->alias]['left'],
'right <' => $saved[$this->alias]['right']
),
'recursive' => -1
));
foreach($children as $child){
$child[$this->alias]['other_model_id'] =
$saved[$this->alias]['other_model_id'];
if (!$this->save($child)){
trigger_error("FAILED", E_USER_ERROR);
}
}
}
}
--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
---
You received this message because you are subscribed to the Google Groups
"CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.