Skip to content
Advertisement

how to order by sum of counts of many columns?

i have posts table and related with likes table ,comments table and shares table i use

 `Post::withCount("likes")->orderByDesc("likes_count")->paginate($per_page);`

to get posts order by likes count .

**i need to get posts order by maxcount of(likes + comments +shares)** ?

ِAny Suggesstion ?

Advertisement

Answer

You can use orderByRaw method

Post::withCount(['likes', 'comments', 'shares'])
    ->orderByRaw('likes_count + comments_count + shares_count DESC')
    ->paginate($per_page);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement