/** * Get the primary key from whatever value you have * * @param string $model_name The name of the model * @param string|integer|Jam_Validated|array $value the value or a container of the value * @return string|integer|NULL NULL when no value is provided or could be extracted. */ public static function primary_key($model_name, $value) { if (!$value) { return NULL; } if ($value instanceof Jam_Validated) { return $value->id(); } if (is_integer($value) or is_numeric($value)) { return (int) $value; } if (is_string($value)) { return $value; } if (is_array($value)) { return Arr::get($value, Jam::meta($model_name)->primary_key()); } }
/** * Get the belonging model for this association using the foreign key, * if the data was changed, use the key from the changed data. * Assign inverse_of * * @param Jam_Validated $model * @param mixed $value changed data * @param boolean $is_changed * @return Jam_Model */ public function get(Jam_Validated $model, $value, $is_changed) { if ($is_changed) { if ($value instanceof Jam_Validated or !$value) { return $value; } $key = Jam_Association::primary_key($this->foreign_model, $value); if ($key) { $item = Jam::find($this->foreign_model, $key); } elseif (is_array($value)) { $item = Jam::build($this->foreign_model); } else { $item = NULL; } if ($item and is_array($value)) { $item->set($value); } } else { $item = Jam::all($this->foreign_model)->join_table($this->branches_table)->on($this->ansestor_key, '=', ':primary_key')->on($this->depth_key, '=', DB::expr(':depth', array(':depth' => 1)))->end()->where($this->branches_table . '.' . $this->descendant_key, '=', $model->id())->first(); } return $this->set($model, $item, $is_changed); }
public function set(Jam_Validated $model, $value, $is_changed) { if ($value instanceof Jam_Model) { if ($this->is_polymorphic()) { $value->{$this->polymorphic_key} = $model->meta()->model(); } if ($model->loaded()) { $value->{$this->foreign_key} = $model->id(); } if ($this->as) { $value->retrieved($this->as, $model); } if ($this->inverse_of) { $value->retrieved($this->inverse_of, $model); } } return $value; }