private function afterSaveThruHasMany($name, $rel, $thru, $new_objs)
{
$thru_cls = $thru->className;
// get the criteria from the named relation to apply to the through relation
$criteria = new CDbCriteria();
$criteria->addCondition($rel->on);
$orig_objs = $this->getRelated($thru->name, true, $criteria);
$orig_by_id = array();
if ($orig_objs) {
foreach ($orig_objs as $orig) {
$orig_by_id[$orig->{$rel->foreignKey}] = $orig;
}
}
if ($new_objs) {
foreach ($new_objs as $i => $new) {
if ($save = @$orig_by_id[$new->getPrimaryKey()]) {
unset($orig_by_id[$new->getPrimaryKey()]);
} else {
$save = new $thru_cls();
}
$save->attributes = $this->getRelationsDefaults($name);
$save->{$thru->foreignKey} = $this->getPrimaryKey();
$save->{$rel->foreignKey} = $new->getPrimaryKey();
if ($save->hasAttribute('display_order')) {
$save->display_order = $i + 1;
}
$a = $save->save();
if (!$a) {
//save->save()) {
throw new Exception("unable to save new through relation {$thru->name} for {$name}" . print_r($save->getErrors(), true));
}
}
}
foreach ($orig_by_id as $orig) {
if (!$orig->delete()) {
throw new Exception("unable to delete redundant through relation {$thru->name} with id {$orig->getPrimaryKey()} for {$name}" . $orig->rel_id);
}
}
}