@@ -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 /**
0 commit comments