Skip to content

Commit

Permalink
[4.x] Use search index in entries fieldtype when possible (#8253)
Browse files Browse the repository at this point in the history
Co-authored-by: Jason Varga <[email protected]>
  • Loading branch information
ryanmitchell and jasonvarga authored Jun 30, 2023
1 parent bcad693 commit 5f7b9e8
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/Fieldtypes/Entries.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Statamic\Query\OrderedQueryBuilder;
use Statamic\Query\Scopes\Filters\Concerns\QueriesFilters;
use Statamic\Query\StatusQueryBuilder;
use Statamic\Search\Result;
use Statamic\Support\Arr;

class Entries extends Relationship
Expand Down Expand Up @@ -114,7 +115,13 @@ public function getIndexItems($request)
$query->orderBy($sort, $this->getSortDirection($request));
}

return $request->boolean('paginate', true) ? $query->paginate() : $query->get();
$entries = $request->boolean('paginate', true) ? $query->paginate() : $query->get();

if ($entries->getCollection()->first() instanceof Result) {
$entries->setCollection($entries->getCollection()->map->getSearchable());
}

return $entries;
}

public function getResourceCollection($request, $items)
Expand Down Expand Up @@ -172,7 +179,20 @@ protected function getIndexQuery($request)
$query = Entry::query();

if ($search = $request->search) {
$query->where('title', 'like', '%'.$search.'%');
$usingSearchIndex = false;
$collections = collect($this->getConfiguredCollections());

if ($collections->count() == 1) {
$collection = Collection::findByHandle($collections->first());
if ($collection && $collection->hasSearchIndex()) {
$query = $collection->searchIndex()->ensureExists()->search($search);
$usingSearchIndex = true;
}
}

if (! $usingSearchIndex) {
$query->where('title', 'like', '%'.$search.'%');
}
}

if ($site = $request->site) {
Expand Down

0 comments on commit 5f7b9e8

Please sign in to comment.