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.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

General Questions /

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

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

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

Go to End



Community Member, 130 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;