Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Creating has_many relation with self

Go to End

4 Posts   3343 Views


Community Member, 545 Posts

11 January 2010 at 12:11pm

Can a dataobject have a has_many relation with self. I'm trying to set up a list of definitions, then include related terms. So each term would have to have a has_many relation with other terms.


Forum Moderator, 5523 Posts

11 January 2010 at 1:16pm

I think you would need a many_many relationship for that as a Definition would have many Related Terms and each of those Related terms would probably have multiple definition it relates to.

You can try add a many_many / belongs_many_many to the object and try it out. I think it *should* be fine with a many_many relationship on itself. Try it out and see what happens :D


Community Member, 2 Posts

18 January 2010 at 8:36am

From IRC:

michaelcole: Hello!
michaelcole: I'm just checking out Silverstripe. How could I model a "has many reference to self" relationship with the ORM?
simon_w: static $has_many = array ('LotsOfMe'=>__CLASS__); static $has_one = array('OneOfMe' => __CLASS__);
michaelcole: Cool! Sounds simple. I like it!


Community Member, 7 Posts

9 May 2013 at 6:59am

Reviving this thread in the context of SilverStripe 3.0...

I'm looking to create a Thesaurus module to support controlled vocabularies and relationships between terms:

  • Alternate Terms (Used For): many terms that are not current, or synonyms to the current term. Using a text field in $db for this now, with a modified search filter to include partial matches from this when searching for Terms.
  • Broader Terms (BT): possibly many more general Terms
  • Narrower Terms (NT): possibly many more specific Terms
  • Related Terms (RT): possibly many Terms with a different (non-hierarchical) relationship

Broader Terms and Narrower Terms are inverses of each other, so I could define one of them in $many_many, and the other in $belongs_many_many. That way, when a Term has a Narrower Term, that Narrower Term lists the original term as a Broader Term. In abstract notation:

if TermA is BT of TermB, then TermB is NT of TermA

Related Terms, though, are bi-directional in themselves. In the same notation as above:

 if TermA is RT of TermB, then TermB is RT of TermA

Is this kind of self-relationship possible without having to manually specify the inverse relationships? If the Data Model doesn't support it naturally, could a code block be added to insert the inverse relationship when the Related Term relationship is added? If so, where would that go and what would it need to look like?