Skip to content

Commit

Permalink
Pull empty IDs instead of filling them with upsert (#2656)
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia authored Jan 17, 2025
1 parent c509115 commit f6b46c1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/Execution/Arguments/UpsertModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Nuwave\Lighthouse\Execution\Arguments;

use Illuminate\Database\Eloquent\Model;
use Nuwave\Lighthouse\Support\Contracts\ArgResolver;

class UpsertModel implements ArgResolver
Expand All @@ -22,14 +23,11 @@ public function __construct(callable $previous)
public function __invoke($model, $args): mixed
{
// TODO consider Laravel native ->upsert(), available from 8.10
$id = $args->arguments['id']
?? $args->arguments[$model->getKeyName()]
?? null;

$idValue = $id?->value;
if ($idValue) {
$id = $this->retrieveID($model, $args);
if ($id) {
$existingModel = $model->newQuery()
->find($idValue);
->find($id);

if ($existingModel !== null) {
$model = $existingModel;
Expand All @@ -38,4 +36,24 @@ public function __invoke($model, $args): mixed

return ($this->previous)($model, $args);
}

/** @return mixed The value of the ID or null */
protected function retrieveID(Model $model, ArgumentSet $args)
{
foreach (['id', $model->getKeyName()] as $key) {
if (! isset($args->arguments[$key])) {
continue;
}

$id = $args->arguments[$key]->value;
if ($id) {
return $id;
}

// Prevent passing along empty IDs that would be filled into the model
unset($args->arguments[$key]);
}

return null;
}
}
10 changes: 10 additions & 0 deletions tests/Utils/Models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tests\Utils\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
Expand Down Expand Up @@ -48,6 +49,15 @@ final class Post extends Model
use Searchable;
use SoftDeletes;

/** @return Attribute<int, int> */
protected function id(): Attribute
{
return Attribute::make(
get: fn (mixed $_, array $attributes): int => $attributes[$this->primaryKey],
set: fn (int $id) => [$this->primaryKey => $id],
);
}

/** @return \Illuminate\Database\Eloquent\Relations\MorphMany<\Tests\Utils\Models\Activity, $this> */
public function activity(): MorphMany
{
Expand Down

0 comments on commit f6b46c1

Please sign in to comment.