WanWizard/Datamapper2 — Issue #6: Additional Methods for Nested Sets Extension
Author: WanWizard
Created: 2011-11-08 21:15:37+00:00
State: open
Labels: Feature, Pending

By Ryan Herriman:

The nested sets extension as it stands is a great start, but there are additional methods that could benefit people if they existed. Here are a few I've written for a Category tree, at the model level:

/**
* Returns the immediate descendant nodes for the current category.
* @return object the updated DataMapper object
*/
public function get_children() {
return
$this->get_clone()
->where(array('left_id >' => $this->left_id, 'left_id <' => $this->right_id))
->where_subquery($this->get_clone()->level() + 1, $this->_depth_subquery())
->get();
}

/**
* Filters categories by their tree-depth level.
* @param int $level
* @return DataMapper Returns self for method chaining.
*/
public function where_depth($level) {
return $this->where_subquery(intval($level), $this->_depth_subquery());
}

/**
* Builds a subquery to calculate node depth.
*/
private function _depth_subquery() {
return $this->get_clone()->select_func('COUNT', '@id', 'depth')->where('left_id < ${parent}.left_id AND right_id > ${parent}.right_id');
}

Obviously these would need to be altered to make use of $_leftindex, $_rightindex, and potentially multiple roots. get_children() could also be made to accept a $node parameter. I actually considered making these changes to the extension myself, but didn't want them to be wiped out by future updates to DataMapper.