/**
* Saves the active record if changed, and creates a relationship to the specified
* $Relationship if provided. Both this and relationship will be saved before the join
* is made
*
* @param ifx_Model $Relationship
* @return mixed
*/
public function save(ifx_Model &$Relationship = null)
{
//Have we been passed a relationship to save
if ($Relationship instanceof ifx_Model) {
//If this isnt loaded, try and save it first
if (!$this->is_loaded() && !$Relationship->is_loaded()) {
if ($this->save() === FALSE) {
return FALSE;
}
}
//Make sure the relationship is already created
//if(!$Relationship->is_loaded()){
// if($Relationship->save() === FALSE) return FALSE;
//}
if ($this->_relationship_is_1NF($Relationship)) {
//Set this relation column to the foreign ID
$this->{$this->_1NF_relationship_field($Relationship)} = $Relationship->id();
//Try and save as usual
return $this->_save_row();
//Test to see if the relationship is 2NF
} elseif ($this->_relationship_is_2NF($Relationship)) {
//In this or the other
if ($this->_2NF_Relationship_is_foreign($Relationship)) {
$Relationship->{$this->_id()} = $this->id();
return $Relationship->save();
} else {
if (!$Relationship->is_loaded()) {
if (!$Relationship->save()) {
return false;
}
}
$this->{$Relationship->_id()} = $Relationship->id();
return $this->save();
}
//Test to see if the relationship has a join table
} elseif ($this->_relationship_is_3NF($Relationship)) {
//Get the join table
$JoinTable = $this->_3NF_relationship_table($Relationship);
//Insert the record into the join table
$this->db->set($this->_id(), $this->id());
$this->db->set($Relationship->_id(), $Relationship->id());
$this->db->insert($JoinTable);
return $this->db->affected_rows() == 1;
} else {
show_error('Unable to save relationship. Relationship is undefined between ' . $this->_table() . ' and ' . $Relationship->_table());
}
} else {
//Run any pre-save defaults - extended by the implementor
$this->before_save();
return $this->_save_row();
}
}