Jump to:

23481 Posts in 18965 Topics by 2878 members

General Questions

SilverStripe Forums » General Questions » how to get many-many related object? (solved using ComponentSet)

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Page: 1
Go to End
Author Topic: 596 Views
  • prawnstar
    Community Member
    116 Posts

    how to get many-many related object? (solved using ComponentSet) Link to this post

    I'm trying to contruct an array from a class and it's many-many related object and I don't understand how to get the related many-many object part.

    I have a class that has a many-many relationship with a dataobject.

    class SomeClass extends Page {
       public static $many_many = array(
          'Categories' => 'Category'

    class Category extends DataObject {
       public static $belongs_many_many = array(
          'SomeClasses' => 'SomeClass'

    In another class I want to access both the parent and the related data to construct the array.

    class MyPage_Controller extends Page_Controller {
       $foo = DataObject::get('SomeClass'...);
          foreach($foo as $bar) {
             $blah1 = $bar->MenuTitle;
             $blah2 = $bar->Content;
             $blah3 = $bar->Categories;
          $myarray = array(

    How do I get the many-many related Categories?
    $blah3 = $bar->Categories;

    Thanks in advance for any assistance!

    In my foreach statement, I include:

    $mycategory = $product->Categories();

    Which returns a ComponentSet. With that I can access my related object by running it through another foreach() statement:

    foreach($mycategory as $category) {
    $somevar = $category->CategoryName;


Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.