From 70fcb80e3ff3d971bd18f5136997412590b7032f Mon Sep 17 00:00:00 2001 From: d-inevitable Date: Tue, 17 Apr 2012 02:55:22 +0300 Subject: [PATCH] Lazy-loading tables in relationships. --- lib/Relationship.php | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/Relationship.php b/lib/Relationship.php index 58540d446..47255f2e1 100644 --- a/lib/Relationship.php +++ b/lib/Relationship.php @@ -649,10 +649,27 @@ public function __construct($options=array()) //infer from class_name if (!$this->foreign_key) $this->foreign_key = array(Inflector::instance()->keyify($this->class_name)); - - $this->primary_key = array(Table::load($this->class_name)->pk[0]); } + /** + * Magic method, the getter. Lazy calculation of the primary_key. + * Aside from a slight performance gain it prevents an error when the + * referenced table doesn't exist yet (the relation is marked but the + * table doesn't exist and all the foreign keys are null). + * + * Why is this needed only in BelongsTo? Because for HasOne/Many the primary key + * always exists. In those cases we can't be sure about the foreign key, but that's + * infered without SQL queries + */ + public function __get($name) + { + if($name=='primary_key' && !isset($this->primary_key)) { + $this->primary_key = array(Table::load($this->class_name)->pk[0]); + } + return @$this->$name; + } + + public function load(Model $model) { $keys = array();