首页 > 解决方案 > 如何在 laravel 中转换 where 匹配查询?

问题描述

我想将以下查询转换为 Laravel ORM

$sql = "SELECT * FROM snippets WHERE MATCH(snippets_name,seo_description,snippets_description,snippet_tags) 
          AGAINST (' ".$query."' IN BOOLEAN MODE) LIMIT " . $start . "," . $limit;

我尝试了以下代码

但没有得到想要的结果

 $searchdata = DB::table('snippets')
        ->selectRaw("*")
        ->whereRaw("MATCH(snippets_name,seo_description,snippets_description,snippet_tags) AGAINST (' ".$query."' IN BOOLEAN MODE)")
        ->paginate(20);

标签: phplaravel

解决方案


你实际上得到了什么结果?

我之前使用 Eloquent 实现了 FULLTEXT 搜索,并建议将MATCH子句移动到 SELECT 中,并按它返回的分数排序。

此外,paginate()原始查询部分效果不佳,因此最好使用take()(limit) 和skip()(offset) 创建自己的分页。

最后,您应该使用准备好的查询绑定,而不是将$query变量添加到原始 SQL 中。

这可能对您有用:

\DB::table('snippets')
    ->select([
        '*',
        \DB::raw("MATCH(snippets_name, seo_description, snippets_description, snippet_tags) AGAINST (? IN BOOLEAN MODE) AS score"),
    ])
    ->take($limit)
    ->skip($start)
    ->havingRaw('score > 0')
    ->orderBy('score', 'DESC')
    ->setBindings([$query])
    ->get();

我已经包括havingRaw()排除任何得分为 0 的结果,这可能是无关紧要的。


推荐阅读