/** * Get the value of a field. * * @throws Sprig_Exception field does not exist * @param string field name * @return mixed */ public function __get($name) { if ( ! $this->_init) { // The constructor must always be called first $this->__construct();
// This object is about to be loaded by mysql_fetch_object() or similar $this->state('loading'); }
if ( ! isset($this->_fields[$name])) { throw new Sprig_Exception(':name model does not have a field :field', array(':name' => get_class($this), ':field' => $name)); }
if (isset($this->_related[$name])) { // Shortcut to any related object return $this->_related[$name]; }
$field = $this->_fields[$name];
if ($this->changed($name)) { $value = $this->_changed[$name]; } elseif (array_key_exists($name, $this->_original)) { $value = $this->_original[$name]; }
if ($field instanceof Sprig_Field_ForeignKey) { if ( ! isset($this->_related[$name])) { $model = Sprig::factory($field->model);
if ($field instanceof Sprig_Field_HasMany) { if ($field instanceof Sprig_Field_ManyToMany) { if (isset($value)) { if (empty($value)) { return new Database_Result_Cached(array(), ''); } else { $query = DB::select() ->where($model->pk(), 'IN', $value); } } else { $query = DB::select() ->join($field->through) ->on($model->fk($field->through, $field->foreign_field), '=', $model->pk(TRUE)) ->where($this->fk($field->through, $name), '=', $this->{$this->_primary_key}); } } else { if (isset($value)) { $query = DB::select() ->where($model->pk(), 'IN', $value); } else { $query = DB::select() ->where($model->fk(NULL, $field->foreign_field), '=', $this->{$this->_primary_key}); } }
$related = $model->load($query, NULL);
if ( ! $this->changed($name)) { // We can assume this is the original value because no // changed value exists $this->_original[$name] = $field->value($related); } } elseif ($field instanceof Sprig_Field_BelongsTo) { $related = $model->values(array($model->pk() => $value)); } elseif ($field instanceof Sprig_Field_HasOne) { $related = $model->values(array($this->_model => $this->{$this->_primary_key})); }
$value = $this->_related[$name] = $related; } }
return $value; }
|