1

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?

subs
  • 179
  • 1
  • 11

2 Answers2

1

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.

Stephen
  • 13
  • 3
1

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...

PsychoMo
  • 699
  • 5
  • 17
  • Will a belongs_many_many relationship be required in order for this to work? – subs May 07 '19 at 21:23
  • I have generally found that `belongs_many_many` is not required (although you should really have an inverse `many_many`). The `ManyManyList` is responsible for generating the join table in the database, so it _shouldn't_ be :-) – PsychoMo May 09 '19 at 16:27