我正在编写Laravel中的搜索功能,但我只能搜索不是理想解决方案的完整查询。我的意思是,如果我传递一个像“lorem%20ipsum”这样的查询,我只得到“lorem ipsum”的结果,并且我没有得到“lorem”或“ipsum”的部分匹配。谁能告诉我一些关于如何最好地完成这项任务的想法?
这是我目前的完整搜索代码:
routes.php文件
Route::get('{lang}/search/{query}', 'HomeController@searchPages');
HomeController.php
public function searchPages($lang, $query) {
$searchResults = Search::acme($query, $lang);
return View::make('search.search')
->with('searchResults', $searchResults);
}
模型/ page.php文件
class Page extends Eloquent {
public function scopeSearch($query, $search)
{
return $query->where(function($query) use ($search)
{
$query->where('title','LIKE', "%$search%")
->orWhere('body', 'LIKE', "%$search%");
});
}
}
的Acme /墙面/ search.php中
namespace Acme\Facades;
use Illuminate\Support\Facades\Facade;
class Search extends Facade {
protected static function getFacadeAccessor()
{
return 'search';
}
}
的Acme /搜索/ SearchServiceProvider.php
namespace Acme\Search;
use Illuminate\Support\ServiceProvider;
class SearchServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('search', 'Acme\Search\Search');
}
}
的Acme /搜索/ search.php中
namespace Acme\Search;
use Illuminate\Support\Collection;
use Page;
class Search {
public function pages($search)
{
return Page::search($search)->get();
}
public function acme($query, $lang)
{
return new Collection(Page::join('langs', 'langs.id', '=', 'pages.lang_parent_id')
->where('title', 'LIKE', '%'.$query.'%')
->orWhere('body', 'LIKE', '%'.$query.'%')
->where('code', '=', $lang)
->get()
->toArray());
}
}
答案 0 :(得分:1)
您需要遍历搜索文本并建立雄辩,例如:
$db_query = Page::join('langs', 'langs.id', '=', 'pages.lang_parent_id');
$my_search_text_arr = explode(' ',$query);
$first = true
for_each($my_search_text_arr as $my_search_text){
if($first){
$db_query = $db_query->where('title', 'LIKE', '%'.$my_search_text.'%');
$first = false;
}else{
$db_query = $db_query->orWhere('title', 'LIKE', '%'.$my_search_text.'%');
}
}
return new Collection($db_query
->where('code', '=', $lang)
->get()
->toArray());