php - 如何在 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);
解决方案
你实际上得到了什么结果?
我之前使用 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 的结果,这可能是无关紧要的。
推荐阅读
- c++ - cin.clear() 将 EOF 留在流中?
- c# - C# 如何将 Selenium WebElement 保留在内存中以便有时间获取其详细信息
- scala - 如何将我的应用程序打包为多个档案?
- python - 无法使用 cv2 调整图像大小
- javascript - 如何在 react-redux 的 axios.get 方法中传递登录用户的 ID?
- r - R mixdist 包中的泊松分布
- c++ - VK_ERROR_INCOMPATIBLE_DRIVER 与 Mac OS 和 Vulkan MoltenVK
- python - 命令出错,退出状态为 1:python setup.py egg_info 检查日志以获取完整的命令输出
- node.js - 如何获取发出请求的用户的 ID
- c# - GStreamer-sharp 无法创建管道