diff --git a/src/ElasticSearch/SearchFactory.php b/src/ElasticSearch/SearchFactory.php index 7e56084..8b20d88 100644 --- a/src/ElasticSearch/SearchFactory.php +++ b/src/ElasticSearch/SearchFactory.php @@ -26,6 +26,7 @@ public static function create(Builder $builder, array $options = []): Search $boolQuery = new BoolQuery(); $boolQuery = static::addWheres($builder, $boolQuery); $boolQuery = static::addWhereIns($builder, $boolQuery); + $boolQuery = static::addWhereNotIns($builder, $boolQuery); if (! empty($builder->query)) { $boolQuery->add($query, BoolQuery::MUST); } @@ -54,7 +55,7 @@ public static function create(Builder $builder, array $options = []): Search */ private static function hasWhereFilters($builder): bool { - return static::hasWheres($builder) || static::hasWhereIns($builder); + return static::hasWheres($builder) || static::hasWhereIns($builder) || static::hasWhereNotIns($builder); } /** @@ -92,6 +93,22 @@ private static function addWhereIns($builder, $boolQuery): BoolQuery return $boolQuery; } + /** + * @param Builder $builder + * @param BoolQuery $boolQuery + * @return BoolQuery + */ + private static function addWhereNotIns($builder, $boolQuery): BoolQuery + { + if (static::hasWhereNotIns($builder)) { + foreach ($builder->whereNotIns as $field => $arrayOfValues) { + $boolQuery->add(new TermsQuery((string) $field, $arrayOfValues), BoolQuery::MUST_NOT); + } + } + + return $boolQuery; + } + /** * @param Builder $builder * @return bool @@ -109,4 +126,13 @@ private static function hasWhereIns($builder): bool { return isset($builder->whereIns) && ! empty($builder->whereIns); } + + /** + * @param Builder $builder + * @return bool + */ + private static function hasWhereNotIns($builder): bool + { + return isset($builder->whereNotIns) && ! empty($builder->whereNotIns); + } } diff --git a/tests/Feature/SearchTest.php b/tests/Feature/SearchTest.php index a6cef7b..e9da78b 100644 --- a/tests/Feature/SearchTest.php +++ b/tests/Feature/SearchTest.php @@ -47,6 +47,14 @@ public function test_search_with_filters(): void $this->assertEquals($iphonePromoUsedAndLikeNew->count(), $iphonePromoUsedAndLikeNewAmount); $this->assertInstanceOf(Product::class, $iphonePromoUsedAndLikeNew->first()); + + $iphonePromoNotUsedAndNotLikeNew = Product::search('iphone') + ->where('price', 100) + ->whereNotIn('type', ['used', 'like new']) + ->get(); + + $this->assertEquals($iphonePromoNotUsedAndNotLikeNew->count(), $iphonePromoNewAmount); + $this->assertInstanceOf(Product::class, $iphonePromoNotUsedAndNotLikeNew->first()); } public function test_search_with_custom_filter()