Skip to content

Commit 5ff53e2

Browse files
committed
fix(laravel): keep the child identifier of a BelongsTo link when both 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.
1 parent 2d66cdb commit 5ff53e2

6 files changed

Lines changed: 136 additions & 9 deletions

File tree

‎src/Laravel/Eloquent/Metadata/IdentifiersExtractor.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace ApiPlatform\Laravel\Eloquent\Metadata;
1515

16+
use ApiPlatform\Laravel\Eloquent\State\LinksHandler;
1617
use ApiPlatform\Metadata\HttpOperation;
1718
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
1819
use ApiPlatform\Metadata\Link;
@@ -44,6 +45,14 @@ public function getIdentifiersFromItem(object $item, ?Operation $operation = nul
4445

4546
private function getIdentifierValue(object $item, Link $link): mixed
4647
{
48+
if ($item instanceof Model && $link->getFromProperty() && null !== ($identifier = $link->getIdentifiers()[0] ?? null)) {
49+
$alias = LinksHandler::LINK_IDENTIFIER_ALIAS_PREFIX.$identifier;
50+
51+
if (\array_key_exists($alias, $item->getAttributes())) {
52+
return $item->getAttributes()[$alias];
53+
}
54+
}
55+
4756
if (is_a($item, $link->getFromClass(), true)) {
4857
return $this->getEloquentProperty($item, $link->getIdentifiers()[0]);
4958
}

‎src/Laravel/Eloquent/State/LinksHandler.php‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@
3535
*/
3636
final class LinksHandler implements LinksHandlerInterface
3737
{
38+
/**
39+
* Prefix of the column alias carrying the identifier of the child model when a BelongsTo link is followed.
40+
*/
41+
public const LINK_IDENTIFIER_ALIAS_PREFIX = 'api_platform_link_';
42+
3843
public function __construct(
3944
private readonly Application $application,
4045
private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
@@ -156,17 +161,13 @@ private function buildQuery(Builder $builder, Link $link, mixed $identifier): Bu
156161
$child = $relation->getParent();
157162
$model = $builder->getModel();
158163

159-
$builder = $builder
164+
return $builder
160165
->join($child->getTable(), $relation->getQualifiedForeignKeyName(), '=', $relation->getQualifiedOwnerKeyName())
161166
->where($child->qualifyColumn($identifierField), $identifier)
162-
->select($model->qualifyColumn('*'));
163-
164-
// The child identifier is read back by the IdentifiersExtractor to build the IRI.
165-
if ($identifierField !== $model->getKeyName()) {
166-
$builder->addSelect($child->qualifyColumn($identifierField));
167-
}
168-
169-
return $builder;
167+
->select($model->qualifyColumn('*'))
168+
// The child identifier is read back by the IdentifiersExtractor to build the IRI. It is aliased
169+
// as it may share its name with a column of the related model (both are often called "id").
170+
->addSelect($child->qualifyColumn($identifierField).' as '.self::LINK_IDENTIFIER_ALIAS_PREFIX.$identifierField);
170171
}
171172

172173
if ($relation instanceof HasOneOrMany || $relation instanceof BelongsToMany) {

‎src/Laravel/Tests/EloquentTest.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
use Workbench\App\Http\Requests\StoreSlotRequest;
2424
use Workbench\App\Models\GrandSon;
2525
use Workbench\App\Models\PostWithMorphMany;
26+
use Workbench\App\Models\Pupil;
27+
use Workbench\App\Models\Teacher;
2628
use Workbench\Database\Factories\AreaFactory;
2729
use Workbench\Database\Factories\AuthorFactory;
2830
use Workbench\Database\Factories\AuthorWithGroupFactory;
@@ -527,6 +529,20 @@ public function testBelongsToReturnsTheRelatedItem(): void
527529
$this->assertSame(['/api/grand_sons/3'], $json['sons']);
528530
}
529531

532+
public function testBelongsToKeepsTheChildIdentifierWhenBothKeysAreNamedId(): void
533+
{
534+
$first = Teacher::create(['name' => 'first']);
535+
$second = Teacher::create(['name' => 'second']);
536+
Pupil::create(['name' => 'a', 'teacher_id' => $second->getKey()]);
537+
Pupil::create(['name' => 'b', 'teacher_id' => $first->getKey()]);
538+
539+
$res = $this->get('/api/pupils/1/teacher', ['Accept' => ['application/ld+json']]);
540+
$res->assertOk();
541+
$json = $res->json();
542+
$this->assertSame('/api/pupils/1/teacher', $json['@id']);
543+
$this->assertSame('second', $json['name']);
544+
}
545+
530546
public function testHasMany(): void
531547
{
532548
GrandSonFactory::new()->count(1)->create();
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace Workbench\App\Models;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use Illuminate\Database\Eloquent\Model;
18+
use Illuminate\Database\Eloquent\Relations\BelongsTo;
19+
20+
#[ApiResource]
21+
class Pupil extends Model
22+
{
23+
protected $fillable = ['name', 'teacher_id'];
24+
25+
public function teacher(): BelongsTo
26+
{
27+
return $this->belongsTo(Teacher::class);
28+
}
29+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace Workbench\App\Models;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use ApiPlatform\Metadata\Get;
18+
use ApiPlatform\Metadata\Link;
19+
use Illuminate\Database\Eloquent\Model;
20+
21+
#[ApiResource]
22+
#[ApiResource(
23+
uriTemplate: '/pupils/{pupilId}/teacher',
24+
uriVariables: [
25+
'pupilId' => new Link(fromClass: Pupil::class, fromProperty: 'teacher', identifiers: ['id']),
26+
],
27+
operations: [new Get()]
28+
)]
29+
class Teacher extends Model
30+
{
31+
protected $fillable = ['name'];
32+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
use Illuminate\Database\Migrations\Migration;
15+
use Illuminate\Database\Schema\Blueprint;
16+
use Illuminate\Support\Facades\Schema;
17+
18+
return new class extends Migration {
19+
public function up(): void
20+
{
21+
Schema::create('teachers', static function (Blueprint $table): void {
22+
$table->id();
23+
$table->string('name');
24+
$table->timestamps();
25+
});
26+
27+
Schema::create('pupils', static function (Blueprint $table): void {
28+
$table->id();
29+
$table->string('name');
30+
$table->foreignId('teacher_id')->constrained();
31+
$table->timestamps();
32+
});
33+
}
34+
35+
public function down(): void
36+
{
37+
Schema::dropIfExists('pupils');
38+
Schema::dropIfExists('teachers');
39+
}
40+
};

0 commit comments

Comments
 (0)