Skip to content

Commit

Permalink
Lazy-loading tables in relationships.
Browse files Browse the repository at this point in the history
  • Loading branch information
gsuess committed Apr 16, 2012
1 parent 1b3a4bb commit 70fcb80
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/Relationship.php
Expand Up @@ -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();
Expand Down

0 comments on commit 70fcb80

Please sign in to comment.