From f8486058889b88b549be4abc7240df575772306d Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Sat, 5 Dec 2026 01:23:59 +0530 Subject: [PATCH] Add `@whereDoesntHaveConditions` directive `@whereHasConditions` lets clients filter a query by the existence of related models that match dynamic conditions, but there was no counterpart to filter by their absence. Excluding records related to a given model while keeping records without any related models required letting clients build `HAS` conditions with `operator: LT` and `amount: 1` through `@whereConditions`, with a client-controlled relation name. `@whereDoesntHaveConditions` works like `@whereHasConditions`, but constrains the relation with `< 1` instead of `>= 1`, which Eloquent turns into `NOT EXISTS`, just like `whereDoesntHave()`. It supports the same `relation`, `columns`, `columnsEnum` and `handler` arguments and infers the relation from argument names following the convention `doesntHave{$RELATION}`. Passing an empty object filters for models without any related model, `null` leaves the query unchanged. Resolves #1646 --- docs/master/api-reference/directives.md | 4 + .../eloquent/complex-where-conditions.md | 81 ++++- .../WhereDoesntHaveConditionsDirective.php | 67 ++++ .../WhereHasConditionsDirective.php | 16 +- ...WhereDoesntHaveConditionsDirectiveTest.php | 330 ++++++++++++++++++ 5 files changed, 495 insertions(+), 3 deletions(-) create mode 100644 src/WhereConditions/WhereDoesntHaveConditionsDirective.php create mode 100644 tests/Integration/WhereConditions/WhereDoesntHaveConditionsDirectiveTest.php diff --git a/docs/master/api-reference/directives.md b/docs/master/api-reference/directives.md index 530c53d33..41d53329b 100644 --- a/docs/master/api-reference/directives.md +++ b/docs/master/api-reference/directives.md @@ -4362,6 +4362,10 @@ Make sure it has exactly two required fields to ensure the query is valid. The documentation for this directive is found in [`Complex Where Conditions`](../eloquent/complex-where-conditions.md#whereconditions). +## @whereDoesntHaveConditions + +The documentation for this directive is found in [`Complex Where Conditions`](../eloquent/complex-where-conditions.md#wheredoesnthaveconditions). + ## @whereHasConditions The documentation for this directive is found in [`Complex Where Conditions`](../eloquent/complex-where-conditions.md#wherehasconditions). diff --git a/docs/master/eloquent/complex-where-conditions.md b/docs/master/eloquent/complex-where-conditions.md index 16fe31291..4aec32b3c 100644 --- a/docs/master/eloquent/complex-where-conditions.md +++ b/docs/master/eloquent/complex-where-conditions.md @@ -358,6 +358,85 @@ This query would retrieve all persons, no matter if they have a role or not: Lighthouse qualifies column names with the table of the related model, unless they already contain a table name. +### @whereDoesntHaveConditions + +```graphql +""" +Allow clients to filter a query by the absence of a related model. +A dynamically controlled `WHERE` condition applies to the relationship. +""" +directive @whereDoesntHaveConditions( + """ + The Eloquent relationship that the conditions will be applied to. + + This argument can be omitted if the argument name follows the naming convention `doesntHave{$RELATION}`. + For example, if the Eloquent relationship is named `posts`, the argument name must be `doesntHavePosts`. + """ + relation: String + + """ + Restrict the allowed column names to a well-defined list. + This improves introspection capabilities and security. + Mutually exclusive with `columnsEnum`. + """ + columns: [String!] + + """ + Use an existing enumeration type to restrict the allowed columns to a predefined list. + This allows you to re-use the same enum for multiple fields. + Mutually exclusive with `columns`. + """ + columnsEnum: String + + """ + Reference a method that applies the client given conditions to the query builder. + + Expected signature: `( + \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder, + array $whereConditions + ): void` + + Consists of two parts: a class name and a method name, separated by an `@` symbol. + If you pass only a class name, the method name defaults to `__invoke`. + """ + handler: String = "\\Nuwave\\Lighthouse\\WhereConditions\\WhereConditionsHandler" +) on ARGUMENT_DEFINITION +``` + +This directive works like [@whereHasConditions](#wherehasconditions), except that it filters for the absence of related models that match the conditions: + +```graphql +type Query { + people( + doesntHaveRole: _ + @whereDoesntHaveConditions(columns: ["name", "access_level"]) + ): [Person!]! @all +} +``` + +A query for persons who do not have a role with an access level of at least 5 looks like this: + +```graphql +{ + people(doesntHaveRole: { column: ACCESS_LEVEL, operator: GTE, value: 5 }) { + name + } +} +``` + +The result also includes persons that do not have any role. +To retrieve only those, use an empty object as argument value: + +```graphql +{ + people(doesntHaveRole: {}) { + name + } +} +``` + +Using `null` as argument value does not have any effect on the query. + ## Custom operator If Lighthouse's default `SQLOperator` does not fit your use case, you can register a custom operator class. @@ -407,7 +486,7 @@ Make sure to add it after Lighthouse's service provider: ## Custom handler -If you want to take advantage of the schema generation that [@whereConditions](#whereconditions) and [@whereHasConditions](#wherehasconditions) provide. +If you want to take advantage of the schema generation that [@whereConditions](#whereconditions), [@whereHasConditions](#wherehasconditions) and [@whereDoesntHaveConditions](#wheredoesnthaveconditions) provide. Customize the application of arguments to the query builder, you can provide a custom handler. ```graphql diff --git a/src/WhereConditions/WhereDoesntHaveConditionsDirective.php b/src/WhereConditions/WhereDoesntHaveConditionsDirective.php new file mode 100644 index 000000000..371169b78 --- /dev/null +++ b/src/WhereConditions/WhereDoesntHaveConditionsDirective.php @@ -0,0 +1,67 @@ + $whereConditions + ): void` + + Consists of two parts: a class name and a method name, separated by an `@` symbol. + If you pass only a class name, the method name defaults to `__invoke`. + """ + handler: String = "\\Nuwave\\Lighthouse\\WhereConditions\\WhereConditionsHandler" +) on ARGUMENT_DEFINITION +GRAPHQL; + } + + protected function relationNamePrefix(): string + { + return 'doesntHave'; + } + + protected function amountOperator(): string + { + return '<'; + } + + protected function generatedInputSuffix(): string + { + return 'WhereDoesntHaveConditions'; + } +} diff --git a/src/WhereConditions/WhereHasConditionsDirective.php b/src/WhereConditions/WhereHasConditionsDirective.php index a1b9d8ddf..f4d17520a 100644 --- a/src/WhereConditions/WhereHasConditionsDirective.php +++ b/src/WhereConditions/WhereHasConditionsDirective.php @@ -72,7 +72,7 @@ public function handleBuilder(QueryBuilder|EloquentBuilder|Relation $builder, $v 'HAS' => [ 'relation' => $this->relationName(), 'amount' => WhereConditionsServiceProvider::DEFAULT_HAS_AMOUNT, - 'operator' => '>=', + 'operator' => $this->amountOperator(), 'condition' => $value, ], ], @@ -89,13 +89,25 @@ protected function relationName(): string // If the relation name is not set explicitly, we assume the argument name follows a convention and contains the relation name if (is_null($relationName)) { return lcfirst( - Str::after($this->nodeName(), 'has'), + Str::after($this->nodeName(), $this->relationNamePrefix()), ); } return $relationName; } + /** Get the prefix of argument names that follow the naming convention for the relation name. */ + protected function relationNamePrefix(): string + { + return 'has'; + } + + /** Get the comparison operator to test the number of related models that match the conditions against the amount. */ + protected function amountOperator(): string + { + return '>='; + } + protected function generatedInputSuffix(): string { return 'WhereHasConditions'; diff --git a/tests/Integration/WhereConditions/WhereDoesntHaveConditionsDirectiveTest.php b/tests/Integration/WhereConditions/WhereDoesntHaveConditionsDirectiveTest.php new file mode 100644 index 000000000..784c103d5 --- /dev/null +++ b/tests/Integration/WhereConditions/WhereDoesntHaveConditionsDirectiveTest.php @@ -0,0 +1,330 @@ +make(); + $this->assertInstanceOf(User::class, $userWithoutCompany); + $userWithoutCompany->company()->dissociate(); + $userWithoutCompany->save(); + + factory(User::class)->create(); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + { + users( + doesntHaveCompany: {} + ) { + id + } + } + GRAPHQL)->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => (string) $userWithoutCompany->id, + ], + ], + ], + ]); + } + + public function testIgnoreNullCondition(): void + { + $user = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $user); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + { + users( + doesntHaveCompany: null + ) { + id + } + } + GRAPHQL)->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => (string) $user->id, + ], + ], + ], + ]); + } + + public function testWithoutRelationName(): void + { + $user = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $user); + + $otherUser = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $otherUser); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + query ($companyID: Mixed!) { + withoutRelation( + doesntHaveCompany: { + column: "id" + value: $companyID + } + ) { + id + } + } + GRAPHQL, [ + 'companyID' => $user->company_id, + ])->assertExactJson([ + 'data' => [ + 'withoutRelation' => [ + [ + 'id' => (string) $otherUser->id, + ], + ], + ], + ]); + } + + public function testOperatorOr(): void + { + $users = factory(User::class, 4)->create(); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + query ($firstCompanyID: Mixed!, $thirdCompanyID: Mixed!) { + users( + doesntHaveCompany: { + OR: [ + { + column: "id" + value: $firstCompanyID + } + { + column: "id" + value: $thirdCompanyID + } + ] + } + ) { + id + } + } + GRAPHQL, [ + 'firstCompanyID' => $users[0]->company_id, + 'thirdCompanyID' => $users[2]->company_id, + ])->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => (string) $users[1]->id, + ], + [ + 'id' => (string) $users[3]->id, + ], + ], + ], + ]); + } + + public function testWhereDoesntHaveBelongsToMany(): void + { + $role = factory(Role::class)->create(); + $this->assertInstanceOf(Role::class, $role); + + $otherRole = factory(Role::class)->create(); + $this->assertInstanceOf(Role::class, $otherRole); + + $userWithRole = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $userWithRole); + $userWithRole->roles()->attach($role); + + $userWithOtherRole = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $userWithOtherRole); + $userWithOtherRole->roles()->attach($otherRole); + + $userWithBothRoles = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $userWithBothRoles); + $userWithBothRoles->roles()->attach([$role->id, $otherRole->id]); + + $userWithoutRoles = factory(User::class)->create(); + $this->assertInstanceOf(User::class, $userWithoutRoles); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + query ($roleID: Mixed!) { + users( + doesntHaveRoles: { + column: "id" + value: $roleID + } + ) { + id + } + } + GRAPHQL, [ + 'roleID' => $role->id, + ])->assertExactJson([ + 'data' => [ + 'users' => [ + [ + 'id' => (string) $userWithOtherRole->id, + ], + [ + 'id' => (string) $userWithoutRoles->id, + ], + ], + ], + ]); + } + + public function testWhereDoesntHaveNestedRelationWithDotNotation(): void + { + $company = factory(Company::class)->create(); + $this->assertInstanceOf(Company::class, $company); + + $userOfCompany = factory(User::class)->make(); + $this->assertInstanceOf(User::class, $userOfCompany); + $userOfCompany->company()->associate($company); + $userOfCompany->save(); + + $postOfUserOfCompany = factory(Post::class)->make(); + $this->assertInstanceOf(Post::class, $postOfUserOfCompany); + $postOfUserOfCompany->user()->associate($userOfCompany); + $postOfUserOfCompany->save(); + + $postOfUserOfOtherCompany = factory(Post::class)->create(); + $this->assertInstanceOf(Post::class, $postOfUserOfOtherCompany); + + $userWithoutCompany = factory(User::class)->make(); + $this->assertInstanceOf(User::class, $userWithoutCompany); + $userWithoutCompany->company()->dissociate(); + $userWithoutCompany->save(); + + $postOfUserWithoutCompany = factory(Post::class)->make(); + $this->assertInstanceOf(Post::class, $postOfUserWithoutCompany); + $postOfUserWithoutCompany->user()->associate($userWithoutCompany); + $postOfUserWithoutCompany->save(); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + query ($companyID: Mixed!) { + posts( + doesntHaveUserCompany: { + column: "id" + value: $companyID + } + ) { + id + } + } + GRAPHQL, [ + 'companyID' => $company->id, + ])->assertExactJson([ + 'data' => [ + 'posts' => [ + [ + 'id' => (string) $postOfUserOfOtherCompany->id, + ], + [ + 'id' => (string) $postOfUserWithoutCompany->id, + ], + ], + ], + ]); + } + + public function testWhereDoesntHaveHasManySameTableRelationship(): void + { + $parent = factory(Location::class)->create(); + $this->assertInstanceOf(Location::class, $parent); + + $child = factory(Location::class)->make(); + $this->assertInstanceOf(Location::class, $child); + $child->parent()->associate($parent); + $child->save(); + + $otherParent = factory(Location::class)->create(); + $this->assertInstanceOf(Location::class, $otherParent); + + $otherChild = factory(Location::class)->make(); + $this->assertInstanceOf(Location::class, $otherChild); + $otherChild->parent()->associate($otherParent); + $otherChild->save(); + + $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL' + query ($doesntHaveChildren: QueryLocationsDoesntHaveChildrenWhereDoesntHaveConditions) { + locations(doesntHaveChildren: $doesntHaveChildren) { + id + } + } + GRAPHQL, [ + 'doesntHaveChildren' => [ + 'column' => 'ID', + 'value' => $child->id, + ], + ])->assertExactJson([ + 'data' => [ + 'locations' => [ + [ + 'id' => (string) $child->id, + ], + [ + 'id' => (string) $otherParent->id, + ], + [ + 'id' => (string) $otherChild->id, + ], + ], + ], + ]); + } +}