From dc92dd264d3ddac94265ecb1a3cb9d466a44ead1 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Fri, 16 Mar 2012 13:01:48 -0500 Subject: [PATCH] Adding auto detection of intermediate table names. Signed-off-by: Taylor Otwell --- laravel/database/eloquent/model.php | 2 +- .../relationships/has_many_and_belongs_to.php | 18 +++++++++++++++++- laravel/helpers.php | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) 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. *