2017-05-29 73 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