Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ridwanhoquepro's avatar

I need an eloquent query to show list of blogs as per ranking

I have articles table, having column ´total_ratings´

I want to calculate ´total_ratings´ such a way that can produce me

3 articles from most likes,

2 articles from most views,

2 articles from most recent,

2 articles from less likes

by using following query (as it is most optimised and by single query)

´Article::orderByDesc("total_ratings")->paginate(9)´

N.B. : If same article matches in most likes and most views then should show once in most likes only and for all other criteria no duplication allowed.

$total_ratings = ($totalLikes * $ratingPerLike) + ($totalViews * $ratingPerView) + ($totalRecents * $ratingPerRecent) + ($totalLessEngaged * $ratingPerLessEngaged)

I want to set the values of $ratingPerLike, $ratingPerView, $ratingPerRecent, $ratingPerLessEngaged such a way, as it includes set of 9 articles per page having 4 criteria ( 3+2+2+2 ) ratio automatically.

For example :

By running query

´Article::orderByDesc("total_ratings")->paginate(9)´

we can see on 1st page:-

assume 3 articles of most liked by visitor have ´total_ratings´ 1018, 1017, 1016

assume 2 articles of most viewed by visitor have ´total_ratings´ 1015, 1014

assume 2 articles of most recently submitted by author have ´total_ratings´ 1013, 1012

assume 2 articles of lest liked by visitor have ´total_ratings´ 1011, 1010

we can see on 2nd page:-

assume 3 articles of most liked by visitor have ´total_ratings´ 1009, 1008, 1007

assume 2 articles of most viewed by visitor have ´total_ratings´ 1006, 1005

assume 2 articles of most recently submitted by author have ´total_ratings´ 1004, 1003

assume 2 articles of lest liked by visitor have ´total_ratings´ 1002, 1001

and so on

Now the problem is, how to design a perfect algorithm as it produces above result ?

0 likes
0 replies

Please or to participate in this conversation.