使用Laravel根据多个条件按相关性排序



我在基于多个条件使用order by时遇到问题。具有最多填充信息的用户应该显示在顶部,然后显示具有较少填充信息的那个用户。

$users = User::where('status',1)  
->withCount('reviews')
->with('reviews','about')
->orderByRaw("CASE WHEN is_native != '0' AND photo != '' THEN 0  ELSE 1 END")// how i can match the about us relationship value here? means if user have added about intro then it should come first and reviews count? 
->paginate(10);

这是我关于用户的关系

public function about()
{
return $this->hasOne('AppUserAbout', 'user_id')->select('about');
}

注意:我正试图用CASE来做这件事,如果还有其他好的选择,你可以指出。

谢谢

这意味着你必须按about的计数排序,然后按review计数排序,这将得到你想要的结果:

$users = User::where('status',1)  
->withCount(['reviews','about'])
->with('reviews','about')
->orderByRaw('about_count desc,reviews_count desc')
->paginate(10);

现在,具有"about"的用户将拥有about_count=1,其他用户则拥有about_count =0

正如@OMR建议的那样,您可以这样做。但您不需要使用原始查询

$users = User::where('status',1)  
->withCount(['reviews','about'])
->with('reviews','about')
->orderBy('about_count','desc')
->orderBy('reviews_count','desc')
->paginate(10);

最新更新