[eluser]OverZealous[/eluser]
[quote author="KSiimson" date="1254780618"]What would be the best approach to delete all the relationships associated with an object?[/quote]
There are several ways. You can first unrelated all of them, then save the new ones (fine for small numbers of related items):
Code:
$countries = $object->country->select('id')->get();
$object->delete($countries->all);
// already looked up $new_countries elsewhere
$object->save($new_countries);
You could also write some code to loop through the list of countries, removing the old ones, and then saving the new ones (better if you have more than 5 or so related items):
Code:
$new_country_ids = array(...); // array of IDs
// loop through existing relationships, and remove old ones
$countries = $object->country->select('id')->get();
foreach($countries->all as $c) {
$idx = array_search($c->id, $new_country_ids);
if($idx === FALSE) {
$object->delete($c);
} else {
// optional, but saves a few queries
unset($new_country_ids[$ids]);
}
}
// now look up the new countries, and save them
$new_countries = new Country();
$new_countries->where_in('id', $new_country_ids)->get();
$object->save($new_countries->all);
// if you want to use countries now, you'll need to re-look them up:
$object->country->get();
In the end, DMZ has to remove each non-related object, and then add each new object. In the background, DMZ does some cleanup work.