Get Related Pages, or: Filter By Many_Many Relation

On our Slack community channel today one question was, how to get all other pages with the same tags like the current page. The solution - once you found it - seems to simple to be true.

We have a Page class with a many_many to our RelationTags like:


class Page extends SiteTree {

	private static $many_many = array(

	        'Relationtags' => 'Relationtag'


	public function getCMSFields() {

		  $fields = parent::getCMSFields();

			$field = TagField::create(






			    ->setShouldLazyLoad(true) // tags should be lazy loaded

			    ->setCanCreate(true);     // new tag DataObjects can be created

			$fields->addFieldToTab('Root.Main', $field);

		  return $fields;



And of course the Tag Dataobject with the reverse $belongs_to:


class Relationtag extends DataObject {

    private static $db = array(

        'Title' => 'Varchar(200)',


    private static $belongs_many_many = array(

        'Pages' => 'Page'



Now how can we get all other Pages with the same tags? Our getter might look like this:

    public function getRelatedcontent(){

        return Page::get()->filter('Relationtags.ID', $this->Relationtags()->column('ID'))->exclude('ID', $this->ID);


This way we get all other pages with at least one similar tag from our database.

This solution was tested in SilverStripe 3.5 and might work in previous versions.

Rate this post (4 rating(s))

Post your comment


No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments