Browse Source

* Add static::fetch() for grabbing an array of objects
* Add $this->related() to allow pulling relationships

Nathaniel van Diepen 7 years ago
parent
commit
aa12355ee5
1 changed files with 27 additions and 0 deletions
  1. 27 0
      orm.abstract.class.php

+ 27 - 0
orm.abstract.class.php

@@ -228,6 +228,13 @@
 		public static function each(callable $fn, int $start = null, int $amount = null){
 			self::each_where($fn, null, $start, $amount);
 		}
+		public static function fetch(array $filter = null, int $start = null, int $amount = null){
+			$results = [];
+			self::each_where(function($item) use($results){
+				$results[] = $item;
+			}, $filter, $start, $amount);
+			return $results;
+		}
 		public static function str_replace_first($search, $replace, $source) {
 			$explode = explode($search, $source);
 			$shift = array_shift($explode);
@@ -337,5 +344,25 @@
 				return in_array($key, $this->_changed);
 			}
 		}
+		public function related(string $name){
+			if(isset($this->_related[$name])){
+				return $this->_related[$name];
+			}else{
+				$class = "Model\\{$name}";
+				if(self::$aliases['belongs_to'][$name]){
+					$this->_related[$name] = $class::fetch([static::$foreign_key => $this->id]);
+				}elseif(self::$aliases['has_one'][$name]){
+					$this->_related[$name] = $class::fetch([$this->name.static::$foreign_key_suffix => $this->id]);
+				}elseif(self::$aliases['has_many'][$name]){
+					//$this->_related[$name] = $class::fetch([$this->name.static::$foreign_key_suffix => $this->id]);
+					throw new Exception("has_many relationships are not implemented yet");
+				}
+			}
+			if(isset($this->_related[$name])){
+				return $this->_related[$name];
+			}else{
+				throw new Exception("Relationship {$name} does not exist");
+			}
+		}
 	}
 ?>