Skip to content
Open
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions src/Laravel/Eloquent/Metadata/IdentifiersExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Laravel\Eloquent\Metadata;

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

private function getIdentifierValue(object $item, Link $link): mixed
{
if ($item instanceof Model && $link->getFromProperty() && null !== ($identifier = $link->getIdentifiers()[0] ?? null)) {
$alias = LinksHandler::LINK_IDENTIFIER_ALIAS_PREFIX.$identifier;

if (\array_key_exists($alias, $item->getAttributes())) {
return $item->getAttributes()[$alias];
}
}

if (is_a($item, $link->getFromClass(), true)) {
return $this->getEloquentProperty($item, $link->getIdentifiers()[0]);
}
Expand Down
21 changes: 15 additions & 6 deletions src/Laravel/Eloquent/State/LinksHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
*/
final class LinksHandler implements LinksHandlerInterface
{
/**
* Prefix of the column alias carrying the identifier of the child model when a BelongsTo link is followed.
*/
public const LINK_IDENTIFIER_ALIAS_PREFIX = 'api_platform_link_';

public function __construct(
private readonly Application $application,
private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
Expand Down Expand Up @@ -153,12 +158,16 @@ private function buildQuery(Builder $builder, Link $link, mixed $identifier): Bu
}

if ($relation instanceof BelongsTo) {
return $builder->getModel()
->join(
$relation->getParent()->getTable(),
$relation->getParent()->getQualifiedKeyName(),
$identifier
);
$child = $relation->getParent();
$model = $builder->getModel();

return $builder
->join($child->getTable(), $relation->getQualifiedForeignKeyName(), '=', $relation->getQualifiedOwnerKeyName())
->where($child->qualifyColumn($identifierField), $identifier)
->select($model->qualifyColumn('*'))
// The child identifier is read back by the IdentifiersExtractor to build the IRI. It is aliased
// as it may share its name with a column of the related model (both are often called "id").
->addSelect($child->qualifyColumn($identifierField).' as '.self::LINK_IDENTIFIER_ALIAS_PREFIX.$identifierField);
}

if ($relation instanceof HasOneOrMany || $relation instanceof BelongsToMany) {
Expand Down
31 changes: 31 additions & 0 deletions src/Laravel/Tests/EloquentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase;
use Workbench\App\Http\Requests\StoreSlotRequest;
use Workbench\App\Models\GrandSon;
use Workbench\App\Models\PostWithMorphMany;
use Workbench\App\Models\Pupil;
use Workbench\App\Models\Teacher;
use Workbench\Database\Factories\AreaFactory;
use Workbench\Database\Factories\AuthorFactory;
use Workbench\Database\Factories\AuthorWithGroupFactory;
Expand Down Expand Up @@ -512,6 +515,34 @@ public function testBelongsTo(): void
$this->assertEquals($json['sons'][0], '/api/grand_sons/1');
}

public function testBelongsToReturnsTheRelatedItem(): void
{
GrandSonFactory::new()->count(3)->create();
$grandFather = GrandSon::findOrFail(3)->grandfather;

$res = $this->get('/api/grand_sons/3/grand_father', ['Accept' => ['application/ld+json']]);
$res->assertOk();
$json = $res->json();
$this->assertEquals($json['@id'], '/api/grand_sons/3/grand_father');
$this->assertSame($grandFather->getKey(), $json['idGrandFather']);
$this->assertSame($grandFather->getAttribute('name'), $json['name']);
$this->assertSame(['/api/grand_sons/3'], $json['sons']);
}

public function testBelongsToKeepsTheChildIdentifierWhenBothKeysAreNamedId(): void
{
$first = Teacher::create(['name' => 'first']);
$second = Teacher::create(['name' => 'second']);
Pupil::create(['name' => 'a', 'teacher_id' => $second->getKey()]);
Pupil::create(['name' => 'b', 'teacher_id' => $first->getKey()]);

$res = $this->get('/api/pupils/1/teacher', ['Accept' => ['application/ld+json']]);
$res->assertOk();
$json = $res->json();
$this->assertSame('/api/pupils/1/teacher', $json['@id']);
$this->assertSame('second', $json['name']);
}

public function testHasMany(): void
{
GrandSonFactory::new()->count(1)->create();
Expand Down
29 changes: 29 additions & 0 deletions src/Laravel/workbench/app/Models/Pupil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Workbench\App\Models;

use ApiPlatform\Metadata\ApiResource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[ApiResource]
class Pupil extends Model
{
protected $fillable = ['name', 'teacher_id'];

public function teacher(): BelongsTo
{
return $this->belongsTo(Teacher::class);
}
}
32 changes: 32 additions & 0 deletions src/Laravel/workbench/app/Models/Teacher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Workbench\App\Models;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Link;
use Illuminate\Database\Eloquent\Model;

#[ApiResource]
#[ApiResource(
uriTemplate: '/pupils/{pupilId}/teacher',
uriVariables: [
'pupilId' => new Link(fromClass: Pupil::class, fromProperty: 'teacher', identifiers: ['id']),
],
operations: [new Get()]
)]
class Teacher extends Model
{
protected $fillable = ['name'];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
public function up(): void
{
Schema::create('teachers', static function (Blueprint $table): void {
$table->id();
$table->string('name');
$table->timestamps();
});

Schema::create('pupils', static function (Blueprint $table): void {
$table->id();
$table->string('name');
$table->foreignId('teacher_id')->constrained();
$table->timestamps();
});
}

public function down(): void
{
Schema::dropIfExists('pupils');
Schema::dropIfExists('teachers');
}
};
Loading