From df70987679f3aa3660f3ef1118071a3208010da2 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Tue, 3 Apr 2012 10:48:01 -0500 Subject: [PATCH] added sync method to has_many relationship. --- .../eloquent/relationships/has_many.php | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/laravel/database/eloquent/relationships/has_many.php b/laravel/database/eloquent/relationships/has_many.php index b80d3844..d5622a41 100644 --- a/laravel/database/eloquent/relationships/has_many.php +++ b/laravel/database/eloquent/relationships/has_many.php @@ -12,6 +12,40 @@ public function results() return parent::get(); } + /** + * Sync the association table with an array of models. + * + * @param array $models + * @return bool + */ + public function sync(array $models) + { + $current = $this->table->lists($this->model->key()); + + // When syncing the has many relationship, we'll just spin the attributes and + // create a fresh model instances for each row. If the "id" is set on the + // array of attributes, we'll set the exists flag to true for update. + foreach ($models as $attributes) + { + $attributes[$this->foreign_key()] = $this->base->get_key(); + + $model = $this->fresh_model($attributes); + + $id = $model->get_key(); + + $model->exists = ( ! is_null($id) and in_array($id, $current)); + + // Before saving we'll force the entire model to be "dirty" so all of + // the attributes are saved. It shouldn't affect the updates as + // saving all the attributes shouldn't hurt anything. + $model->original = array(); + + $model->save(); + } + + return true; + } + /** * Initialize a relationship on an array of parent models. *