Nic*_*rth 2 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);
Run Code Online (Sandbox Code Playgroud)
这个作品和拉回到与存在于我的任何选定列的关键字的所有条目。在这种情况下纽约从city_town
列,北约克郡从county
列。
我需要查询来检查这些关键字的每一行,并带回所有出现这些关键字的条目,然后是随后出现一个或多个的条目(我的示例现在是这样做的)。
在此先感谢任何可以提供帮助的人。
好的,也许有些SQL魔术师可以为您提供更好的SQL解决方案。但在此之前...
这就是我如何使用Laravel 集合(用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();
Run Code Online (Sandbox Code Playgroud)