Skip to content

Self-referential relationships generate incorrect route names #189

@geoidesic

Description

@geoidesic

Description

When using self-referential relationships in CakePHP with the JSON API plugin, the route name generation fails because the registry alias is incorrectly set to the association name instead of the source table name.

Example

Given a People table with a self-referential relationship named Administratives:

// In PeopleTable.php
$this->belongsToMany('Administratives', [
'className' => 'People',
// ... other options
]);

The plugin attempts to generate a route name using:

$from = $this->getRepository()->getRegistryAlias(); // Returns "Administratives"
$type = $association->getName(); // Returns "Administratives"
$routeName = "CrudJsonApi.{$from}:{$type}"; // Results in "CrudJsonApi.Administratives:Administratives"

This fails because:

  1. The registry alias becomes "Administratives" (the association name) instead of "People"
  2. The resulting route "CrudJsonApi.Administratives:Administratives" doesn't exist
  3. The correct route should be "CrudJsonApi.People:Administratives"

Current Behavior

  • Regular relationships work correctly (e.g., Enquiries -> People as Administratives)
  • Self-referential relationships fail with MissingRouteException

Expected Behavior

Both regular and self-referential relationships should generate correct route names using the controller name rather than the potentially confused registry alias.

Fix

Use the controller name from routing parameters instead of the registry alias:

['controller' => $controllerName] = $this->getRepositoryRoutingParameters($this->getRepository());
$from = $controllerName; // Returns "People" consistently

This works because:

  1. _getRepositoryRoutingParameters() returns the correct controller name regardless of relationship type
  2. For regular relationships, it produces the same result as before
  3. For self-referential relationships, it fixes the registry alias confusion
  4. It respects plugin prefixes and custom resource paths

Additional Context

This issue only affects self-referential relationships where the association name differs from the table name. The fix maintains compatibility with all other relationship types while correctly handling the self-referential case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions