Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions app/src/Lib/Traits/TableMetaTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,13 @@ public function bindPluginRelations() {
$activeModels = $Plugins->getActivePluginModels('all');

foreach(array_keys($activeModels) as $entryPointModelName) {
$PluginTable = TableRegistry::getTableLocator()->get($entryPointModelName);

// Not all Entry Point Models are Tables (eg: Jobs).
$tableClassName = \Cake\Core\App::className($entryPointModelName, 'Model/Table', 'Table');
if(!$tableClassName) {
continue;
}

$PluginTable = TableRegistry::getTableLocator()->get($entryPointModelName);

if(method_exists($PluginTable, 'getHasManyPluginRelations')) {
$pluginRelations = $PluginTable->getHasManyPluginRelations($tableName);
Expand All @@ -93,7 +97,37 @@ public function bindPluginRelations() {
$config['className'] = $r['targetModel'];
}

$this->hasMany($alias, $config);
$assocAlias = $alias;
if (strpos($alias, '.') !== false) {
// CakePHP will strip the plugin prefix when assigning the alias key.
// For example, 'CoreApi.MatchCallbacks' becomes 'MatchCallbacks'.
$assocAlias = explode('.', $alias, 2)[1];
}

// If another plugin defines a relation with the same base name
// (e.g., 'OtherApi.MatchCallbacks' also becoming 'MatchCallbacks'),
// it causes an "Association alias is already set" conflict.
// To prevent this overlap, we inspect the existing alias's target class.
// If the classes differ, we dynamically generate a unique alias
// (e.g., 'OtherApiMatchCallbacks') by prepending the plugin name.
if ($this->associations()->has($assocAlias)) {
$existing = $this->associations()->get($assocAlias);
$expectedClassName = $config['className'] ?? $r['targetModel'];

if ($existing->getClassName() !== $expectedClassName) {
$newAlias = str_replace('.', '', $r['targetModel']);
if ($alias !== $r['targetModel']) {
$newAlias .= $alias;
}

$config['className'] = $r['targetModel'];
if (!$this->associations()->has($newAlias)) {
$this->hasMany($newAlias, $config);
}
}
} else {
$this->hasMany($alias, $config);
}
}
}
}
Expand Down