执行全文搜索时,如何根据 Laravel 中的搜索词的相关性进行排序?
迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::dropIfExists('posts');
Schema::create('posts',function (Blueprint $table){
// More columns will be added in next migrations.
$table->id();
$table->string('name');
$table->fulltext(['name']);
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};
型号
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $table="posts";
}
我在控制器中执行全文搜索,如下所示:
class PostController extends Controller
{
public function search()
{
$searchterm = $request->get('searchterm');
$qb = Post::query();
if(!empty($searchterm)){
$qb=$qb->whereFullText(['name'],$searchterm);
}
$page = $request->get('page')??1;
$limit = $request->get('limit')??20;
$results = $qb->offset(($page - 1) * $limit)
->simplePaginate($limit);
return new JsonResponse($results,200);
}
}
但是,我需要弄清楚如何返回控制器中按相关性排序的结果。我希望最接近的匹配项首先出现。有人可以帮忙吗?
放置原始查询部分的方法,例如:
class PostController extends Controller
{
public function search()
{
$searchterm = $request->get('searchterm');
$qb = Post::query();
if(!empty($searchterm)){
$qb=$qb->whereRaw("MATCH(name) AGAINST(? IN BOOLEAN MODE)",["*".$searchterm."*"])
->orderByRaw("MATCH(name) AGAINST(?) DESC", ["*".$searchterm."*"]);
}
$page = $request->get('page')??1;
$limit = $request->get('limit')??20;
$results = $qb->offset(($page - 1) * $limit)
->simplePaginate($limit);
return new JsonResponse($results,200);
}
}
我使用
whereRaw
和 orderByRaw
来对结果进行排序和过滤。