Added related model updating from belongs_to relationship.

This commit is contained in:
Taylor Otwell 2012-03-17 23:14:01 -05:00
parent 68b4e55336
commit fcff36a0ac
4 changed files with 42 additions and 5 deletions

View File

@ -174,6 +174,22 @@ public static function create($attributes)
return ($success) ? $model : false;
}
/**
* Update a model instance in the database.
*
* @param mixed $id
* @param array $attributes
* @return int
*/
public static function update($id, $attributes)
{
$model = new static(array(), true);
if (static::$timestamps) $attributes['updated_at'] = $model->get_timestamp();
return $model->query()->where($model->key(), '=', $id)->update($attributes);
}
/**
* Find a model by its primary key.
*

View File

@ -12,6 +12,17 @@ public function results()
return parent::first();
}
/**
* Update the parent model of the relationship.
*
* @param array $attributes
* @return int
*/
public function update($attributes)
{
return $this->model->update($this->foreign_value(), $attributes);
}
/**
* Set the proper constraints on the relationship table.
*
@ -19,9 +30,7 @@ public function results()
*/
protected function constrain()
{
$foreign = $this->base->get_attribute($this->foreign);
$this->table->where($this->base->key(), '=', $foreign);
$this->table->where($this->base->key(), '=', $this->foreign_value());
}
/**
@ -80,4 +89,14 @@ public function match($relationship, &$children, $parents)
}
}
/**
* Get the value of the foreign key from the base model.
*
* @return mixed
*/
public function foreign_value()
{
return $this->base->get_attribute($this->foreign);
}
}

View File

@ -114,7 +114,9 @@ public function insert($attributes, $joining = array())
*/
public function delete()
{
return $this->joining_table()->where($this->foreign_key(), '=', $this->base->get_key())->delete();
$id = $this->base->get_key();
return $this->joining_table()->where($this->foreign_key(), '=', $id)->delete();
}
/**

View File

@ -57,7 +57,7 @@ public static function foreign($model, $foreign = null)
{
if ( ! is_null($foreign)) return $foreign;
// If the model is an object, we will simply get the class of the object and
// If the model is an object we'll simply get the class of the object and
// then take the basename, which is simply the object name minus the
// namespace, and we'll append "_id" to the name.
if (is_object($model))