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.

General Questions /

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

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




Community Member, 127 Posts

22 October 2011 at 4:39am

Edited: 22/10/2011 10:50am

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;