Is there a way to unlink the many_many relationships in SilverStripe 3 using code?
After a certain date, I want to unpublish a page and unlink all its many many relationships.
How can I do this?
Is there a way to unlink the many_many relationships in SilverStripe 3 using code?
After a certain date, I want to unpublish a page and unlink all its many many relationships.
How can I do this?
Many Many relationships in SilverStripe 3 are unversioned, unless you have a very large number of many many relations there will be no performance impact from maintaining the relationship links when the page is unpublished.
Alternatively, you can remove the relationships during unpublishing using the onBeforeUnpublish hook.
Unlink basically calls $page->Relation()->remove($object);
If you wanted to remove the relations you can use the onBeforeUnpublish()
hook something like:
class Page extends SiteTree
{
public function onBeforeUnpublish()
{
foreach ($this->Relation() as $object) {
$this->Relation()->remove($object);
}
}
}
If you wanted to do this automatically, you might want to add something to your PageController::init()
that loops through all pages that need unpublishing and then unpublish them (I think using Page::doUnpublish()
).
Alternatively, you could write a BuildTask
and then run it via a cron job.
NOTE I haven't tested the code above, it will require some tweaking...