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

Pulling a unique group of parent pages and returning them in a DataObjectSet

Go to End

2 Posts   888 Views


Community Member, 49 Posts

28 June 2011 at 10:28pm

Hey there,

In my project, I have Products, which extend Page.

I also have Brands, which is a Dataobject

Inside a function in Brands_Controller, I have a DataObjectSet of products. What I am wanting to do is return a DataObjectSet of these products Parents. The catch is I only want to return a Parent once. For example, if two products have the same Parent, only put it into the DataObjectSet once.

I've got this working, however I'm concerned with the amount of database calls I will be making with the function below in order to retrieve this set of Parents.

The parents of 'Products' are 'ProductGroups' - you might be familiar with this setup if you've used the ecommerce module.

	 * Return a DataObjectSet of ProductGroups available for this brand.
	 public function ProdGroups(){
		//Function to get all products for this brand....
		$prods = $this->GetTheProducts();
		//If products exist...
			//Array of ParentID's
			$parentIds = array();
			//The container to hold the ProductGroups
			$groups = new DataObjectSet(); 
			//Foreach product...
			foreach($prods as $prod)
				//If the ParentID doesn't exist in $parentIds (i.e. we only want on instance of each parent ID
				if(!in_array($prod->ParentID, $parentIds))
					//Push the parent id into $parentIds
					array_push($parentIds, $prod->ParentID);
					//Push this parent object to $groups
			return $groups;
		} else {
			return false;	

If I have 100 products in 100 different productgroups, Parent() is going to make 100 database queries to get all the objects.

Is there a more streamlined way to pull all these Parents in one database call as opposed to one per unique Parent?


Community Member, 49 Posts

29 June 2011 at 6:31am

I've taken another look at this function, and instead of pushing each Parent to a DataObjectSet using a foreach loop, I have imploded the Array of $parentIds and used:

$groups = DataObject::get('ProductGroup',"SiteTree_Live.ID IN ($parentIdString)");

I'm more comfortable knowing that is one DB call over potentially hundreds. I'd still really appreciate some feedback if someone else thinks there is a better way?