Laravel 5全文搜索

9
我有一个数据库表,其中包含名字和姓氏字段。我需要检查Asiapay提供的信用卡持有人姓名是否属于我的旅行团(即我的数据库表中的记录)。问题在于提供的信用卡持有人是完整的姓名(单个字段)。
到目前为止,我的选择有:
- 使用全文搜索 - 使用https://github.com/atomescrochus/laravel-string-similarities,但不确定要考虑多少百分比才算正确
我需要一些关于字符串比较的其他库和策略的建议。
PS:我无法将连接的名字和姓氏与持有人姓名进行比较,因为旅行文件中的名称有时与信用卡上的名称不同(例如护照中的“John Foo Doe”与信用卡中的“John Doe”)。

你不能将 first_name 和 last_name 连接起来,然后使用 like 来匹配 holder_name 吗? - Kapitan Teemo
我无法比较连接的名字和姓氏与持卡人姓名,因为旅行文件中的名称有时与个人信用卡中的名称不同(例如,护照中的“John Foo Doe”与信用卡中的“John Doe”)。 - kissartisan
3个回答

15

这是如何实现全文搜索的方法:

首先在您的表格上创建一个全文搜索。

// Full Text Index
DB::statement('ALTER TABLE contacts ADD FULLTEXT fulltext_index (firstName, lastName, email)');

那么在你的模型中

$columns = 'firstName,lastName,email';
    $contacts = Contact::where('customer_id', $request->user()->customer_id)
        ->select(['id', 'firstName', 'lastName', 'email', 'phone', 'mobile', 'lastContacted', 'assignedTo', 'createdBy'])
        ->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)", $this->fullTextWildcards($q))
        ->paginate(10);

以下是函数fullTextWildcards,其将空格替换为全文搜索通配符。

protected function fullTextWildcards($term)
{
    // removing symbols used by MySQL
    $reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
    $term = str_replace($reservedSymbols, '', $term);

    $words = explode(' ', $term);

    foreach ($words as $key => $word) {
        /*
         * applying + operator (required word) only big words
         * because smaller ones are not indexed by mysql
         */
        if (strlen($word) >= 3) {
            $words[$key] = '*' . $word . '*';
        }
    }

    $searchTerm = implode(' ', $words);

    return $searchTerm;
}

这个完美地运作了......(有没有其他方法可以不使用Mysql原始查询) - dipenparmar12

2

-1
你可以通过空格来分割该字符串:
$name = explode(' ', $name);

然后获取名字:

$first = array_shift($name); 

然后获取姓氏:

$last = array_pop($name);

然后剩下的部分应该就相对简单了。祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接