Skip to content

Commit 083af67

Browse files
committed
Get map algo from Meilisearch implem
1 parent ec37d64 commit 083af67

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/Scout/ScoutEngine.php

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@
2828

2929
use function array_column;
3030
use function array_flip;
31+
use function array_key_exists;
3132
use function array_map;
3233
use function array_merge;
33-
use function array_search;
3434
use function assert;
3535
use function call_user_func;
3636
use function class_uses_recursive;
@@ -286,12 +286,27 @@ public function map(Builder $builder, $results, $model): Collection
286286
return $model->newCollection();
287287
}
288288

289-
$ids = array_column($results, '_id');
289+
$objectIds = array_column($results, '_id');
290+
$objectIdPositions = array_flip($objectIds);
290291

291-
return $model->getScoutModelsByIds($builder, $ids)
292-
->filter(fn (Model $model) => in_array($model->getScoutKey(), $ids))
293-
->sortBy(fn (Model $model) => array_search($model->getScoutKey(), $ids))
294-
->values();
292+
return $model->getScoutModelsByIds(
293+
$builder,
294+
$objectIds,
295+
)->filter(function ($model) use ($objectIdPositions) {
296+
return array_key_exists($model->getScoutKey(), $objectIdPositions);
297+
})->map(function ($model) use ($results, $objectIdPositions) {
298+
$result = $results[$objectIdPositions[$model->getScoutKey()]] ?? [];
299+
300+
foreach ($result as $key => $value) {
301+
if (substr($key, 0, 1) === '_') {
302+
$model->withScoutMetadata($key, $value);
303+
}
304+
}
305+
306+
return $model;
307+
})->sortBy(function ($model) use ($objectIdPositions) {
308+
return $objectIdPositions[$model->getScoutKey()];
309+
})->values();
295310
}
296311

297312
/**

0 commit comments

Comments
 (0)