2017-04-30 46 views
2

我是laravel新手,正在嘗試編寫一個搜索API,示例url位於下方。排序'+'表示升序,' - '表示降序。查詢,類別部分已完成,我正在獲得所需的結果,但排序部分仍然存在。我不知道如何動態地進行多重排序。我可以給orderBy中的排序數組,像where()子句[['rating','asc'],['distance','desc']]。我看過很多帖子,人們通過再次調用orderBy()和agin來做多個排序,但是這是靜態的,例如orderBy('rating','asc')->orderBy('distance','desc'),我該如何動態地做到這一點?Laravel:按api進行動態查詢排序

本地主機:8000 /搜索Q =查詢&貓=範疇&排序= +評級,距離d, - 年齡

class SearchController extends Controller 
{ 
    public function index(Request $request){ 

     $sort = explode(',', $request->sort); 

     return DB::table('posts')->join('users', 'users.id', '=', 'posts.user_id')->join('locations', 'locations.id', '=', 'users.location_id')->join('main_categories', 'main_categories.id', '=', 'posts.main_category_id')->select('posts.*', 'users.*', 'locations.address', 'main_categories.name as cat', DB::raw('ROUND((6371 * ACOS(COS(RADIANS(31.430443800000003)) * COS(RADIANS(locations.lattitude)) * COS(RADIANS(locations.longitude) - RADIANS(74.280726)) + SIN(RADIANS(31.430443800000003)) * SIN(RADIANS(locations.lattitude)))),2) AS DISTANCE'))->where([['posts.title','like','%'.$request->q.'%'],['main_categories.name', '=', $request->cat]])->orwhere([['posts.description','like','%'.$request->q.'%'],['main_categories.name', '=', $request->cat]])->orderBy($request->sort,'DESC')->get(); 
    } 
} 

回答

1
$query // your query 

foreach($sorts as $sort) 
{ 
    $query->orderBy($sort,'DESC') 
} 

$sortedQuery = $query->get();