Browse Source

added sync method to has_many relationship.

Taylor Otwell 13 years ago
parent
commit
df70987679
1 changed files with 34 additions and 0 deletions
  1. 34 0
      laravel/database/eloquent/relationships/has_many.php

+ 34 - 0
laravel/database/eloquent/relationships/has_many.php

@@ -12,6 +12,40 @@ class Has_Many extends Has_One_Or_Many {
 		return parent::get();
 		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.
 	 * Initialize a relationship on an array of parent models.
 	 *
 	 *