Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pull empty IDs instead of filling them with upsert #2656

Merged
merged 2 commits into from
Jan 17, 2025
Merged
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
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
Loading