Skip to content

fix(laravel): return the related item of a BelongsTo link - #8901

Open
BenMacha wants to merge 3 commits into
api-platform:5.0from
BenMacha:fix-laravel-belongs-to-link-5-0
Open

BenMacha wants to merge 3 commits into
api-platform:5.0from
BenMacha:fix-laravel-belongs-to-link-5-0

Conversation

@BenMacha

Copy link
Copy Markdown
Contributor
Q A
Branch? 5.0
Tickets -
License MIT
Doc PR -

A sub-resource that follows a BelongsTo relation always returns the first row of the parent table, whatever the URI variable is. With the workbench models:

#[ApiResource(
    uriTemplate: '/grand_sons/{id_grand_son}/grand_father',
    uriVariables: ['id_grand_son' => new Link(fromClass: GrandSon::class, fromProperty: 'grandfather', identifiers: ['id_grand_son'])],
    operations: [new Get()],
)]
class GrandFather extends Model {}

GET /api/grand_sons/3/grand_father, where grandson 3 belongs to grandfather 3:

  • before: grandfather 1 ("idGrandFather": 1, "sons": ["/api/grand_sons/1"])
  • after: grandfather 3 ("idGrandFather": 3, "sons": ["/api/grand_sons/3"])

The LinksHandler built join(child_table, child.pk, <id>), so the ON clause compared the child key to a quoted identifier and never involved the parent table. In practice that is a cross join, and first() picks the first parent. Because of select *, the child's columns (name, created_at...) also overwrote the parent's. The existing testBelongsTo creates a single record, so it could not catch this. On MySQL the quoted identifier becomes an unknown column, so I expect an error there rather than a wrong row.

The fix joins on the foreign key, filters on the child identifier and selects only the parent columns. The child identifier is still selected when it is not the parent key, because the IdentifiersExtractor reads it back to build the IRI (/api/grand_sons/3/grand_father). Covered by testBelongsToReturnsTheRelatedItem in src/Laravel/Tests/EloquentTest.php.

The BelongsTo branch of the LinksHandler joined the child table on "child.pk = <id>", which
never matches the parent row: the query returned the first row of the parent table whatever the
URI variable was. Join on the foreign key, filter on the child identifier and only select the
parent columns (plus the child identifier, read back to build the IRI).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T08:59:52.248418Z ee99ab3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee99ab3813

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

->select($model->qualifyColumn('*'));

// The child identifier is read back by the IdentifiersExtractor to build the IRI.
if ($identifierField !== $model->getKeyName()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the child identifier when key names collide

When both sides of a BelongsTo link use the common id primary-key name, this condition skips adding the joined child ID, leaving only the target model's id in the result. IdentifiersExtractor::getIdentifierValue() reads the link identifier from that result to build the nested IRI, so if the child and parent IDs differ, the response uses the parent's ID in the path. Preserve the child identifier separately, such as under an alias, rather than treating equal column names as equal values.

Useful? React with 👍 / 👎.

… keys share a name

The child identifier was only selected when its column name differed from the key name of the
related model. With two models keyed by "id", the related model's own "id" was read back
instead, so the IRI of the returned item contained the wrong identifier.

The child identifier is now always selected under an alias and read back from it by the
IdentifiersExtractor.
@BenMacha
BenMacha force-pushed the fix-laravel-belongs-to-link-5-0 branch from 7e6f8e2 to 5ff53e2 Compare November 30, 2026 12:35

@soyuka soyuka left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the query fix is right. Not a huge fan of the aliased api_platform_link_* column though, it ends up in the model attributes (toArray(), events...). The uri variable is already available: generateRoute passes $context['uri_variables'] to the identifiers extractor

$identifiers = $context['uri_variables'] ?? [];
if (\is_object($resource)) {
try {
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($resource, $identifiersExtractorOperation, $context);
} catch (RuntimeException $e) {
can you read it from there when the item isn't the link's fromClass? And use a subquery instead of the join so no column can collide:

return $builder->whereIn(
    $relation->getQualifiedOwnerKeyName(),
    $child->newQuery()->select($relation->getQualifiedForeignKeyName())->where($child->qualifyColumn($identifierField), $identifier)
);

With that Pupil/Teacher and the migration aren't needed anymore, testBelongsToReturnsTheRelatedItem is enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants