Fazal Rasel
Fazal Rasel

Reputation: 4526

HABTM join table name

In case of Recipe HABTM Ingredient relation, name of join is ingredients_recipes.

Is there any CakePHP method or function that return the name of joinTable between two models?

At present I defined a method on AppModel as-

public function habtmJoinTableName($model){
    $currentModel = Inflector::tableize($this->name);
    $joinModel = Inflector::tableize($model);

    $joinTable = array($currentModel, $joinModel);
    sort($joinTable);
    return join('_', $joinTable);
}

If you don't understand my question please comments. I will try my best to make it clear with my little English knowledge..

Upvotes: 0

Views: 95

Answers (1)

ndm
ndm

Reputation: 60463

There is no built in method that would simply return the join table name for two HABTM associated models, no.

CakePHP generates the table name in a method that fills the association configuration with default values, that is Model::_generateAssociation().

// ...

case 'joinTable':
    $tables = array($this->table, $this->{$class}->table);
    sort($tables);
    $data = $tables[0] . '_' . $tables[1];
    break;

// ...

As you can see it's doing it pretty much the same way as you are, except for that it is using string concatenation (which is faster), and the Model::$table property instead of Model::$name, which might not return the results that you'd expect.

So except for that small possible problem with the name property that you should change to using table, your code should be fine and return the proper table name.

Upvotes: 1

Related Questions