目前我的HomeController看起来像这样:
class HomeController extends BaseController {
public function getHome()
{
$scripts = Script::select('script.*', DB::raw('COALESCE(SUM(vote.rating), 0) as rating'))
->leftJoin('script_vote as vote', 'vote.script_id', '=', 'script.id')
->with('tags')
->orderBy('rating', 'desc')
->orderBy('views', 'desc')
->groupBy('id')
->paginate(8);
return View::make('home')->with('scripts', $scripts);
}
public function postSearch()
{
$input = array(
'query' => Input::get('query'),
'sort_col' => Input::get('sort_col'),
'sort_dir' => Input::get('sort_dir'),
);
$scripts = Script::select('script.*', DB::raw('COALESCE(SUM(vote.rating), 0) as rating'))
->leftJoin('script_vote as vote', 'vote.script_id', '=', 'script.id')
->where('title', 'LIKE', '%' . $input['query'] . '%')
->orderBy($input['sort_col'], $input['sort_dir'])
->orderBy('views', 'desc')
->groupBy('id')
->with('tags')
->paginate(8);
Input::flash();
return View::make('home')->with('scripts', $scripts);
}
}
正如你所看到的,我两次使用(几乎)相同的大查询。我想在postSearch()
函数中调用getHome()
函数,并使用它给出三个参数(query ='',sort_col ='rating',sort_dir ='desc')。这可能吗?
答案 0 :(得分:1)
这里有几种可能性:
private function getScripts(...)
(不那么性感)getScripts(...)
功能(so-lala sexy)答案 1 :(得分:1)
如果您打算经常使用此功能,我会将其移出您的控制器并将其作为Custom Query Scope放入您的模型中。即使作为私人功能,它在Controller中也没有位置。
public function scopeRating($query)
{
return $query->select('script.*', DB::raw('COALESCE(SUM(vote.rating), 0) as rating'))
->leftJoin('script_vote as vote', 'vote.script_id', '=', 'script.id')
->with('tags')
->orderBy('rating', 'desc')
->orderBy('views', 'desc')
->groupBy('id');
}
然后可以像这样调用
Script::rating();