我正在编写搜索脚本,并希望根据用户的查询返回结果。
以下是我的路线: -
Route::get('/search/{city}/{searchquery}', 'SearchController@search');
控制器
public function search($city, $query){
strtolower($query);
$commonWords = array('a','able','about','above','abroad'.....);
$cleanQuery = preg_replace('/\b('.implode('|',$commonWords).')\b/','',$query);
$cleanQuery = $s = preg_replace('/[^a-z0-9]+/i', ' ', $cleanQuery);
$queryarray = explode(' ',$cleanQuery);
$queryarray = array_filter( $queryarray );
$queryarray = array_slice( $queryarray, 0 );
//code to match each query word with MySQL fields such as title, description
return $result;
}
我相信,所有这些逻辑和代码都不应该写在控制器中。我可以用什么来编写逻辑并使用控制器只返回结果
答案 0 :(得分:0)
最简单的方法是使用模型。只需编写一个获取关键字并将其解析为sql查询的方法。您可以使用范围方法来提供更大的灵活性。
public function scopeSearch($q, $keywords)
{
// ... $keywords processing here
$keywordsArray = explode(',', $keywords);
return $query->whereIn('keyword', $keywordsArray);
// OR maybe something like this?
return $query->where('keywords', 'LIKE', '%'. $keywords .'%');
}
您可以在控制器中使用此方法:
$city = new City();
$results = $city->search($keywords)->where(/* additional conditions could be added here */)->get();
即使您决定不使用范围方法,我仍然建议返回查询构建器对象而不是集合,以便提供更好的灵活性,例如在需要时在控制器中实现分页或其他操作。
如果您不害怕添加更多复杂化以获得更多灵活性,您也可以使用存储库。更多相关内容:https://laracasts.com/lessons/repositories-simplified