public function junction($table = null)
{
if ($table === null && $this->_junctionTable) {
return $this->_junctionTable;
}
$tableLocator = $this->tableLocator();
if ($table === null && $this->_through) {
$table = $this->_through;
} elseif ($table === null) {
$tableName = $this->_junctionTableName();
$tableAlias = Inflector::camelize($tableName);
$config = [];
if (!$tableLocator->exists($tableAlias)) {
$config = ['table' => $tableName];
// Propagate the connection if we'll get an auto-model
if (!App::className($tableAlias, 'Model/Table', 'Table')) {
$config['connection'] = $this->source()->connection();
}
}
$table = $tableLocator->get($tableAlias, $config);
}
if (is_string($table)) {
$table = $tableLocator->get($table);
}
$source = $this->source();
$target = $this->target();
$this->_generateSourceAssociations($table, $source);
$this->_generateTargetAssociations($table, $source, $target);
$this->_generateJunctionAssociations($table, $source, $target);
return $this->_junctionTable = $table;
}
/** * Tests that custom foreignKeys are properly trasmitted to involved associations * when they are customized * * @return void */ public function testJunctionWithCustomForeignKeys() { $assoc = new BelongsToMany('Test', ['sourceTable' => $this->article, 'targetTable' => $this->tag, 'foreignKey' => 'Art', 'targetForeignKey' => 'Tag']); $junction = $assoc->junction(); $this->assertEquals('Art', $junction->association('Articles')->foreignKey()); $this->assertEquals('Tag', $junction->association('Tags')->foreignKey()); $inverseRelation = $this->tag->association('Articles'); $this->assertEquals('Tag', $inverseRelation->foreignKey()); $this->assertEquals('Art', $inverseRelation->targetForeignKey()); }