Skip to content

Commit 2d501b3

Browse files
authored
feat(laravel): support composite identifiers within Link (#7342)
1 parent c46c579 commit 2d501b3

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/Laravel/Eloquent/State/LinksHandler.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
2929
use Illuminate\Database\Eloquent\Relations\MorphTo;
3030
use Illuminate\Database\Eloquent\Relations\Relation;
31+
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
3132

3233
/**
3334
* @implements LinksHandlerInterface<Model>
@@ -109,8 +110,22 @@ private function buildQuery(Builder $builder, Link $link, mixed $identifier): Bu
109110
if ($from = $link->getFromProperty()) {
110111
/** @var Model $relatedInstance */
111112
$relatedInstance = $this->application->make($link->getFromClass());
112-
$relatedInstance->setAttribute($relatedInstance->getKeyName(), $identifier);
113-
$relatedInstance->exists = true;
113+
114+
$identifierField = $link->getIdentifiers()[0];
115+
116+
if ($identifierField !== $relatedInstance->getKeyName()) {
117+
$relatedInstance = $relatedInstance
118+
->newQuery()
119+
->where($identifierField, $identifier)
120+
->first();
121+
} else {
122+
$relatedInstance->setAttribute($identifierField, $identifier);
123+
$relatedInstance->exists = true;
124+
}
125+
126+
if (!$relatedInstance) {
127+
throw new NotFoundHttpException('Not Found');
128+
}
114129

115130
/** @var Relation<Model, Model, mixed> $relation */
116131
$relation = $relatedInstance->{$from}();

0 commit comments

Comments
 (0)