Permalink
Browse files

Adding auto detection of intermediate table names.

Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
  • Loading branch information...
1 parent c3d9512 commit dc92dd264d3ddac94265ecb1a3cb9d466a44ead1 @taylorotwell taylorotwell committed Mar 16, 2012
@@ -264,7 +264,7 @@ public function belongs_to($model, $foreign = null)
* @param string $other
* @return Relationship
*/
- public function has_many_and_belongs_to($model, $table, $foreign = null, $other = null)
+ public function has_many_and_belongs_to($model, $table = null, $foreign = null, $other = null)
{
return new Has_Many_And_Belongs_To($this, $model, $table, $foreign, $other);
}
@@ -39,12 +39,28 @@ public function __construct($model, $associated, $table, $foreign, $other)
{
$this->other = $other;
- $this->joining = $table;
+ $this->joining = $table ?: $this->joining($model, $associated);
parent::__construct($model, $associated, $foreign);
}
/**
+ * Determine the joining table name for the relationship.
+ *
+ * By default, the name is the models sorted and concatenated with an underscore.
+ *
+ * @return string
+ */
+ protected function joining($model, $associated)
+ {
+ $models = array(class_basename($model), class_basename($associated));
+
+ sort($models);
+
+ return strtolower($models[0].'_'.$models[1]);
+ }
+
+ /**
* Get the properly hydrated results for the relationship.
*
* @return array
View
@@ -377,6 +377,21 @@ function root_namespace($class, $separator = '\\')
}
/**
+ * Get the "class basename" of a class or object.
+ *
+ * The basename is considered the name of the class minus all namespaces.
+ *
+ * @param object|string $class
+ * @return string
+ */
+function class_basename($class)
+{
+ if (is_object($class)) $class = get_class($class);
+
+ return basename($class);
+}
+
+/**
* Return the value of the given item.
*
* If the given item is a Closure the result of the Closure will be returned.

0 comments on commit dc92dd2

Please sign in to comment.