From 42302a563946e88cca0e2c7b81616d2e59393fb5 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Mon, 4 Jul 2022 15:41:14 +0200 Subject: [PATCH] Implement `@hasManyThrough` directive https://github.com/nuwave/lighthouse/issues/332 --- .../Directives/HasManyThroughDirective.php | 74 +++++++++++++++++++ .../HasManyThroughDirectiveTest.php | 59 +++++++++++++++ tests/Utils/Models/Task.php | 6 ++ 3 files changed, 139 insertions(+) create mode 100644 src/Schema/Directives/HasManyThroughDirective.php create mode 100644 tests/Integration/Schema/Directives/HasManyThroughDirectiveTest.php diff --git a/src/Schema/Directives/HasManyThroughDirective.php b/src/Schema/Directives/HasManyThroughDirective.php new file mode 100644 index 0000000000..3eaf83928d --- /dev/null +++ b/src/Schema/Directives/HasManyThroughDirective.php @@ -0,0 +1,74 @@ +schema = /** @lang GraphQL */ ' + type Post { + id: ID! + } + + type Task { + postComments: [Post!]! @hasManyThrough + } + + type Query { + task: Task! @first + } + '; + + $user = factory(User::class)->create(); + assert($user instanceof User); + + $task = factory(Task::class)->create(); + assert($task instanceof Task); + + $post = factory(Post::class)->make(); + assert($post instanceof Post); + $post->user()->associate($user); + $post->task()->associate($task); + $post->save(); + + $comments = factory(Comment::class, 2)->make(); + foreach ($comments as $comment) { + assert($comment instanceof Comment); + $comment->user()->associate($user); + $comment->post()->associate($post); + $comment->save(); + } + + $this->graphQL(/** @lang GraphQL */ ' + { + task { + postComments { + id + } + } + } + ')->assertJsonCount(2, 'data.task.postComments'); + } +} diff --git a/tests/Utils/Models/Task.php b/tests/Utils/Models/Task.php index c063a00679..8a809a8813 100644 --- a/tests/Utils/Models/Task.php +++ b/tests/Utils/Models/Task.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphOne; @@ -73,6 +74,11 @@ public function post(): HasOne return $this->hasOne(Post::class); } + public function postComments(): HasManyThrough + { + return $this->hasManyThrough(Comment::class, Post::class); + } + public function tags(): MorphToMany { return $this->morphToMany(Tag::class, 'taggable');