我是laravel newbie,我正在尝试编写搜索API,示例网址如下。排序' +'意思是提升和' - '意思是下降。查询,类别部分已完成,我得到了所需的结果,但排序部分仍然存在。我不知道如何动态进行多次排序。我可以按顺序给出一系列排序,例如where()子句[[' rating',' asc'],['距离','降序']]。我看过很多帖子,人们通过再次调用orderBy()和agin进行多次排序,但这是静态的,例如orderBy('rating','asc')->orderBy('distance','desc')
,我怎么能动态地做到这一点?
?本地主机:8000 /搜索Q =查询&安培;猫=类别&安培;排序= +评级,-distance,-age
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();
}
}
答案 0 :(得分:1)
$query // your query
foreach($sorts as $sort)
{
$query->orderBy($sort,'DESC')
}
$sortedQuery = $query->get();