2017-03-07 21 views
2

我在處理多個關鍵字和根據相關性查詢數據庫時遇到問題。我想搜索每一行,如果每行匹配的關鍵字超過1個(根據我選擇的列),請首先對這些條目進行排序。如何使用多個關鍵字從數據庫中獲取和排序最相關的條目Laravel 5

我確實有一些工作,但它只是將列中的關鍵字的所有條目以特定的順序或相關性進行抽取。

拿這個工作示例:

$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); 

這工作,並拉回到與存在於我的任何選定列的關鍵字的所有條目。在這種情況下,來自city_town列的約克列和來自county列的北約克郡列。

我需要的查詢來檢查每個單排這些關鍵字,並帶回條目時這些關鍵字的所有存在,其次是其中一個或多個出現之後(我比如現在做到這一點)。

非常感謝任何人誰可以提供幫助。

+0

可能要考慮使用的索引服務器爲這個,而不是試圖編寫自己的。 – Pitchinnate

回答

4

好吧,也許一些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(); 
+0

幹得好先生!令人印象深刻。我想用你設計的這個新的可愛的系統使用paginate()方法,它似乎沒有工作,猜測這是因爲我們修改了初始查詢,並且該方法在我們的新數組中不再可用? –

+0

我剛剛在網上發現的幾個主題後創建了手動分頁。 [示例這裏](http://stackoverflow.com/questions/30477915/laravel-pagination-not-working-with-array-instead-of-collection?answertab=votes#tab-top)再次感謝! –

+0

謝謝:)我想你可以在分頁結果中使用[' - > getCollection()'](https://laravel.com/api/5.0/Illuminate/Pagination/LengthAwarePaginator.html#method_getCollection)以獲得採集。 – devk

相關問題