Browse Source

Merge pull request #813 from anaxamaxan/patch-3

Allow Model instance or id for first argument in Has_Many_And_Belongs_To::attach()
Taylor Otwell 12 years ago
parent
commit
46f68ab78c

+ 7 - 4
laravel/database/eloquent/relationships/has_many_and_belongs_to.php

@@ -85,12 +85,14 @@ class Has_Many_And_Belongs_To extends Relationship {
 	/**
 	/**
 	 * Insert a new record into the joining table of the association.
 	 * Insert a new record into the joining table of the association.
 	 *
 	 *
-	 * @param  int    $id
-	 * @param  array  $joining
+	 * @param  Model|int    $id
+	 * @param  array  $attributes
 	 * @return bool
 	 * @return bool
 	 */
 	 */
 	public function attach($id, $attributes = array())
 	public function attach($id, $attributes = array())
 	{
 	{
+		if ($id instanceof Model) $id = $id->get_key();
+		
 		$joining = array_merge($this->join_record($id), $attributes);
 		$joining = array_merge($this->join_record($id), $attributes);
 
 
 		return $this->insert_joining($joining);
 		return $this->insert_joining($joining);
@@ -99,12 +101,13 @@ class Has_Many_And_Belongs_To extends Relationship {
 	/**
 	/**
 	 * Detach a record from the joining table of the association.
 	 * Detach a record from the joining table of the association.
 	 *
 	 *
-	 * @param  int   $ids
+	 * @param  array|Model|int   $ids
 	 * @return bool
 	 * @return bool
 	 */
 	 */
 	public function detach($ids)
 	public function detach($ids)
 	{
 	{
-		if ( ! is_array($ids)) $ids = array($ids);
+		if ($ids instanceof Model) $ids = array($ids->get_key());
+		elseif ( ! is_array($ids)) $ids = array($ids);
 
 
 		return $this->pivot()->where_in($this->other_key(), $ids)->delete();
 		return $this->pivot()->where_in($this->other_key(), $ids)->delete();
 	}
 	}