2017-05-29 70 views
0

在laravel 5.2中,我想通過訂單country,然後posts_count,然後images_count獲得用戶。爲此我使用了下面的查詢。如何在laravel 5中排序用戶

User::with(['profiles' => function($query) use ($country){ 
     $query->orderBy(DB::raw('case when country="'.$country.'" then 1 else 2 end'))->orderBy('country', 'ASC'); 
         }]) 
     ->withCount('posts') 
     ->withCount('images') 
     ->orderBy('posts_count', 'desc') 
     ->orderBy('images_count', 'desc') 
     ->get(); 

但此查詢排序用戶可以通過posts_count,然後images_count然後country。 請指導我如何在查詢中首先修復訂單優先級country

回答

1

試試這個

User::with(['profiles' => function($query) use ($country){ 
           $query->orderBy(DB::raw('case when country="'.$country.'" then 1 else 2 end')); 
         }]) 
         ->withCount('posts') 
         ->withCount('images') 
         ->orderBy('country', 'ASC') 
         ->orderBy('posts_count', 'desc') 
         ->orderBy('images_count', 'desc') 
         ->get(); 

不同的方式

DB::table('user')->select(DB::raw("(case when country!='".$country."' then 1 else 2 end)as country"),DB::raw("(count(post))as post"),DB::raw("(count(images))as images")) 
     ->orderBy('country', 'ASC') 
     ->orderBy('posts', 'desc') 
     ->orderBy('images', 'desc') 
     ->get(); 
+0

這沒有奏效。這在'訂單子句'中拋出了'未知列'國家'的錯誤' – Harry

+0

確實需要不同的方法來處理這個 –

+0

。如果它有效。謝謝 – Harry