Skip to content

Commit

Permalink
处理其他数据库不支持 order by field 语句的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
vanry committed Nov 4, 2020
1 parent 4a5500f commit 3459db4
Showing 1 changed file with 8 additions and 18 deletions.
26 changes: 8 additions & 18 deletions src/Engines/TNTSearchEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Laravel\Scout\Builder;
use TeamTNT\TNTSearch\TNTSearch;
use Laravel\Scout\Engines\Engine;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder as Query;
use TeamTNT\TNTSearch\Exceptions\IndexNotFoundException;
Expand Down Expand Up @@ -179,20 +178,21 @@ protected function mapModels(Builder $builder, $results, $model)
{
$this->builder = $builder;

$query = $model->whereIn(
$model->getQualifiedKeyName(),
collect($results['ids'])->values()->all()
);
$query = $model->whereIn($model->getQualifiedKeyName(), $results['ids']);

if ($this->usesSoftDelete($model) && config('scout.soft_delete')) {
$query = $this->handleSoftDelete($query);
}

$query = $this->applyWheres($query);

$query = $this->applyOrders($query, $results['ids']);
$query = $this->applyOrders($query);

return $query->get();
$models = $query->get();

return empty($this->builder->orders) ? $models->sortBy(function ($model) use ($results) {
return array_search($model->getKey(), $results['ids']);
})->values() : $models;
}

/**
Expand Down Expand Up @@ -224,18 +224,8 @@ protected function applyWheres(Query $query)
return $query->where($this->builder->wheres);
}

protected function applyOrders(Query $query, array $ids)
protected function applyOrders(Query $query)
{
if (empty($this->builder->orders)) {
return $query->orderByRaw(
sprintf('field(%s%s,%s)',
DB::getTablePrefix(),
$query->getModel()->getQualifiedKeyName(),
implode(',', array_filter($ids))
)
);
}

return array_reduce($this->builder->orders, function ($query, $order) {
return $query->orderBy($order['column'], $order['direction']);
}, $query);
Expand Down

0 comments on commit 3459db4

Please sign in to comment.