I came up with a neat function for deleting single or multiple relationships while editing a record.
For instance,
Brainstorm
-> id
-> name
-> description
-> author_id
-> data_source_1_id
-> data_source_2_id
DS1 and DS2 cannot be the same and can both be nulled if only 1 source is provided.
However while updating I dont belive you can delete then save… (not sure here and havnt tried…)
But this will search the master object, grab the id of the field you want to delete, create the object of the relation and delete it all for you!
Anyways heres the fun little method I created (just tacked it into the brainstorm model
Sorry for the somewhat confusing nature of the variables lol
/**
* Deleted the relation between the master object
* and its children.
*
* @param varchar $master_obj the name master object loosing the relation(s)
* @param varchar $master_key the column name to get the master object
* @param varchar $master_value the value for the column name
* @param array $remove_objs The relations to be deleted in format ID => array ($class => $coloum_name)
*/
function delete_relation($master_obj,$master_key,$master_value,$remove_objs)
{
$mast_obj = new $master_obj();
$mast_obj->where($master_key,$master_value)->get();
// echo 'Master Object: '.$master_obj.' ( '.$master_key.' => '.$master_value.' )<br>';
foreach ($remove_objs as $remove)
{
foreach ($remove as $key => $val)
{
//echo key($remove).' => '.$key.' => '.$val.'
';
$mast_obj->$val->get();
$obj = new $key();
$obj->where('id',$mast_obj->$val->id)->get();
$delete[$val] = $obj;
}
}
$mast_obj->delete($delete);
}
Then in the controller to delete the records
set an array such as (you need the same format)
the $array[] makes it so you can have multiples of the same (so I could delete DS1 and DS2 at the same time) You can fill this in with a value it wont matter… just as long as the array under it has the $class => $field
$delete[] = array ($class => $field);
and then right before you save call the delete method as such
// Delete any nulled relations
if (isset($delete)) $b->delete_relation($master_class,$master_key,$master_value,$delete);
Simple as that let me know if there are any questions.
BTW I tested and this method works.