我有这个 Laravel 查询,它在表中的两个字段(名称、简介)中搜索匹配的条目:
$data = Listing::select("name", "slug")
->where("name", "LIKE", "%{$q}%")
->orWhere("introduction", "LIKE", "%{$q}%")
->get();
一切正常,除了当“Open ter”作为搜索项($)提供时,它不会提取结果,但有一个名为“Open terms Archive”的条目。当我提供“Terms”作为查询时,该条目包含在结果中。
我的数据库排序规则是utf8mb4_general_ci。这里可能有什么问题?
您可以先通过修剪来删除多个空格。 https://www.php.net/manual/en/function.preg-replace.php
$q = trim(preg_replace('/\s+/', ' ', $q));
$data = Listing::select("name", "slug")
->where(DB::raw("REPLACE(name, ' ', ' ')"), "LIKE", "%{$q}%")
->orWhere(DB::raw("REPLACE(introduction, ' ', ' ')"), "LIKE", "%{$q}%")
->get();
另一种方法是使用 Collate。排序规则根据权重对字符进行排序。字符集中的每个字符都映射到一个权重。 ch
$data = Listing::select("name", "slug")
->where("name", "LIKE", "%{$q}%")
->orWhere("introduction", "LIKE", "%{$q}%")
->orWhere(DB::raw("name COLLATE utf8mb4_general_ci"), "LIKE", "%{$q}%")
->orWhere(DB::raw("introduction COLLATE utf8mb4_general_ci"), "LIKE", "%{$q}%")
->get();
Collate 有助于字符串比较和排序。 https://dev.mysql.com/doc/refman/8.4/en/adding-collation.html#:~:text=A%20collation%20is%20a%20set,orders%20characters%20based%20on%20weights .