Merge branch 'maint/7.0'
[ninja.git] / system / libraries / ORM_Tree.php
blob1c69e53e3f075d0741046cbf18926691c37dd8bc
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * Object Relational Mapping (ORM) "tree" extension. Allows ORM objects to act
4 * as trees, with parents and children.
6 * $Id: ORM_Tree.php 3917 2009-01-21 03:06:22Z zombor $
8 * @package ORM
9 * @author Kohana Team
10 * @copyright (c) 2007-2008 Kohana Team
11 * @license http://kohanaphp.com/license.html
13 class ORM_Tree extends ORM {
15 // Name of the child
16 protected $children;
18 // Parent keyword name
19 protected $parent_key = 'parent_id';
21 /**
22 * Overload ORM::__get to support "parent" and "children" properties.
24 * @param string column name
25 * @return mixed
27 public function __get($column)
29 if ($column === 'parent')
31 if (empty($this->related[$column]))
33 // Load child model
34 $model = ORM::factory(inflector::singular($this->children));
36 if (array_key_exists($this->parent_key, $this->object))
38 // Find children of this parent
39 $model->where($model->primary_key, $this->object[$this->parent_key])->find();
42 $this->related[$column] = $model;
45 return $this->related[$column];
47 elseif ($column === 'children')
49 if (empty($this->related[$column]))
51 $model = ORM::factory(inflector::singular($this->children));
53 if ($this->children === $this->table_name)
55 // Load children within this table
56 $this->related[$column] = $model
57 ->where($this->parent_key, $this->object[$this->primary_key])
58 ->find_all();
60 else
62 // Find first selection of children
63 $this->related[$column] = $model
64 ->where($this->foreign_key(), $this->object[$this->primary_key])
65 ->where($this->parent_key, NULL)
66 ->find_all();
70 return $this->related[$column];
73 return parent::__get($column);
76 } // End ORM Tree