Skip to content

Commit 89d956f

Browse files
committed
Bugfix for empty search terms
1 parent 318f60f commit 89d956f

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
All notable changes to `laravel-cross-eloquent-search` will be documented in this file
44

5+
## 2.2.2 - 2021-09-21
6+
7+
- Bugfix for empty search terms
8+
59
## 2.2.1 - 2021-09-17
610

711
- Bugfix for JSON columns

src/Searcher.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ public function addSearchQueryToBuilder(Builder $builder, ModelToSearchThrough $
351351
*/
352352
private function addRelevanceQueryToBuilder($builder, $modelToSearchThrough)
353353
{
354-
if ($this->orderByDirection !== 'relevance') {
354+
if (!$this->isOrderingByRelevance() || $this->termsWithoutWildcards->isEmpty()) {
355355
return;
356356
}
357357

@@ -428,6 +428,16 @@ protected function buildQueries(): Collection
428428
});
429429
}
430430

431+
/**
432+
* Returns a boolean wether the ordering is set to 'relevance'.
433+
*
434+
* @return boolean
435+
*/
436+
private function isOrderingByRelevance(): bool
437+
{
438+
return $this->orderByDirection === 'relevance';
439+
}
440+
431441
/**
432442
* Compiles all queries to one big one which binds everything together
433443
* using UNION statements.
@@ -444,12 +454,15 @@ protected function getCompiledQueryBuilder(): QueryBuilder
444454
// union the other queries together
445455
$queries->each(fn (Builder $query) => $firstQuery->union($query));
446456

447-
if ($this->orderByDirection === 'relevance') {
457+
if ($this->isOrderingByRelevance() && $this->termsWithoutWildcards->isNotEmpty()) {
448458
return $firstQuery->orderBy('terms_count', 'desc');
449459
}
450460

451461
// sort by the given columns and direction
452-
return $firstQuery->orderBy(DB::raw($this->makeOrderBy()), $this->orderByDirection);
462+
return $firstQuery->orderBy(
463+
DB::raw($this->makeOrderBy()),
464+
$this->isOrderingByRelevance() ? 'asc' : $this->orderByDirection
465+
);
453466
}
454467

455468
/**

tests/SearchTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,20 @@ public function it_can_sort_by_word_occurrence()
324324
$this->assertTrue($results->first()->is($videoB));
325325
}
326326

327+
/** @test */
328+
public function it_doesnt_fail_when_the_terms_are_empty()
329+
{
330+
Video::create(['title' => 'bar']);
331+
Video::create(['title' => 'foo']);
332+
333+
$results = Search::new()
334+
->add(Video::class)
335+
->orderByRelevance()
336+
->get();
337+
338+
$this->assertCount(2, $results);
339+
}
340+
327341
/** @test */
328342
public function it_uses_length_aware_paginator_by_default()
329343
{

0 commit comments

Comments
 (0)