diff --git a/laravel/database/eloquent/model.php b/laravel/database/eloquent/model.php index 00cba31b..8946bce5 100644 --- a/laravel/database/eloquent/model.php +++ b/laravel/database/eloquent/model.php @@ -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); } diff --git a/laravel/database/eloquent/relationships/has_many_and_belongs_to.php b/laravel/database/eloquent/relationships/has_many_and_belongs_to.php index b4fe924f..4ac55570 100644 --- a/laravel/database/eloquent/relationships/has_many_and_belongs_to.php +++ b/laravel/database/eloquent/relationships/has_many_and_belongs_to.php @@ -39,11 +39,27 @@ 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. * diff --git a/laravel/helpers.php b/laravel/helpers.php index 7507c5d2..68b68602 100644 --- a/laravel/helpers.php +++ b/laravel/helpers.php @@ -376,6 +376,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. *