php - 如何使用多个关键字从数据库中获取和排序最相关的条目 Laravel 5

标签 php mysql sql laravel laravel-5

我在处理多个关键字和根据相关性查询数据库时遇到问题。我想搜索每一行,如果根据我选择的列每行匹配的关键字超过 1 个,则首先对这些条目进行排序。

我确实有一些工作,但它只是以没有特定顺序或相关性的方式提取列中存在的关键字的所有条目。

以这个工作示例为例:

$search_terms = array('York', 'North Yorkshire');

$properties = Property::where(function ($q) use ($search_terms) {
            foreach ($search_terms as $value) {
                $q->orWhere('address1', 'like', "%{$value}%");
                $q->orWhere('address2', 'like', "%{$value}%");
                $q->orWhere('postcode', 'like', "%{$value}%");
                $q->orWhere('city_town', 'like', "%{$value}%");
                $q->orWhere('county', 'like', "%{$value}%");
            }
        })->paginate(25);

这有效并拉回所有带有我所选列中存在的关键字的条目。在本例中,York 来自 city_town 列,North Yorkshire 来自 county 列。

我需要查询来检查这些关键字的每一行,并带回存在这些关键字的 ALL 的条目,然后是一个或多个出现的条目(我的示例现在这样做).

非常感谢任何可以提供帮助的人。

最佳答案

好吧,也许某些 SQL 魔术师可以为您提供更好的 SQL 解决方案。但在那之前……

这就是我使用 Laravel 的方式 collections (用 php 排序):

$search_terms = array('York', 'North Yorkshire');

$properties = Property::where(function ($q) use ($search_terms) {
            foreach ($search_terms as $value) {
                $q->orWhere('address1', 'like', "%{$value}%");
                $q->orWhere('address2', 'like', "%{$value}%");
                $q->orWhere('postcode', 'like', "%{$value}%");
                $q->orWhere('city_town', 'like', "%{$value}%");
                $q->orWhere('county', 'like', "%{$value}%");
            }
        })->paginate(25);

$props = ['address1', 'address2', 'postcode', 'city_town', 'county'];

$properties = $properties->sortByDesc(function($i, $k) use ($search_terms, $props) {
    // The bigger the weight, the higher the record
    $weight = 0;
    // Iterate through search terms
    foreach($search_terms as $searchTerm) {
        // Iterate through properties (address1, address2...)
        foreach($props as $prop) { 
            // Use strpos instead of %value% (cause php)
            if(strpos($i->{$prop}, $searchTerm) !== false)
                $weight += 1; // Increase weight if the search term is found
        }
    }

    return $weight;
});

$properties = $properties->values()->all();

关于php - 如何使用多个关键字从数据库中获取和排序最相关的条目 Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42657297/

相关文章:

php - 获取有关 PHPUnit 测试失败的更多上下文

mysql - 如何在mysql中的CONCAT ("string",列)上创建索引?

mysql - 为什么 MySQL CASE 语句返回 NULL 列?

mysql - MySQL中加入同表临时表

href 中的 PHP Mailgun 错误链接

javascript - 有什么方法可以停止使用 HTML 呈现当前页面

php - 使用 Google Sheets API 更改单元格颜色 (PHP)

MySQL - 如何将 "Using join buffer (Block Nested Loop)"添加到查询中?

php - 如何在 bootstrap 模式中显示 php 搜索结果? Modal 在显示结果后消失了?

Sql 查询在数据库中查找临时表