我在处理多个关键字和根据相关性查询数据库时遇到问题。我想搜索每一行,如果根据我选择的列每行匹配的关键字超过 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/