Laravel MySQL 搜索。允许用户进行自定义布尔搜索。

3

我正在做一个员工管理项目,客户提出了一项新要求,希望允许他们的用户进行自定义布尔搜索。

基本上允许他们使用: AND、OR、NOT、括号和引号。

最佳实现方法是什么?我已经查看了mysql,但它们使用了不同的语法。

这是测试场景:

需求:搜索来自新加坡的Magicians或Barbarians,其等级为Elite或Veteran Level

布尔字符串:("Magician" OR "Barbarian") AND (Elite OR "Veteran Level") and Singaporean

这是我将考虑修改的代码之一,我从Pure PHP based boolean search for strings中获取。

function booleanSearch($content, $search) {
    $criteria = str_getcsv($search, ' ');

    while ($criteria) {
        $not = false;
        $q = array_shift($criteria);

        if (substr($q, 0, 2) === '-"') {
            $not = true;

            while (substr($q, -1) != '"') {
                $q .= " " . array_shift($criteria);
            }

            $q = substr($q, 2, -1);
        }
        else if (substr($q, 0, 1) === '-' && strpos($q, ' ') === false) {
            $not = true;
            $q = substr($q, 1);
        }

        $found = strpos($content, $q) !== false;

        if ($found === $not) {
            return false;
        }
    }

    return true;
}

你是否已经有一些代码或更多上下文信息供我们查看? - Quezler
你需要编写某种解析器。这并不容易。例如,获取括号内的所有字符串(例如,“Magician”或“Barbarian”),然后分割获取标记(例如[Magician,OR,Barbarian]),由于OR是二元运算符,因此您可以获取其左右两侧进行OR比较的内容。NOT是右结合的一元运算符,因此您需要将其与右侧的第一个内容匹配。再次强调,这并不容易。 - apokryfos
@Quezler,我更新了帖子。 - RayzorMamon
1个回答

2

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