If anyone thinks this can be run with a normal fluent query then I’d love to hear about it!<\/strong><\/p>\nThis post is more to illustrate how you’d run a complex query in Laravel, and also how to use a Reddit-esque ranking algorithm (actually this isn’t even the algorithm that Reddit use, but it’s the closest and most popular website that I can liken it to).<\/p>\n
Here’s how to run it within a Laravel app:<\/p>\n
\r\n\r\n$posts['products'] = DB::select(DB::raw("\r\nSELECT\r\nposts.id,\r\nslug,\r\nproduct_price,\r\npost_title,\r\nposts.created_at,\r\nproduct_link,\r\naffiliate_link,\r\nusername,\r\n(SELECT SUM(vote) FROM posts_votes WHERE posts.id = posts_votes.post_id ) as VotesCount\r\nFROM\r\nposts\r\nJOIN\r\nuser\r\nON\r\nposts.post_author=user.id\r\nORDER by\r\n((VotesCount - 1) \/ (TIMESTAMPDIFF(HOUR, posts.created_at, NOW()) + 2)^1.5) DESC\r\n"));\r\n\r\n<\/pre>\n(apologies for the poor formatting above, WordPress is automatically formatting it. I’ll fix soon)<\/p>\n
Since the query returns an object, we can turn it into an array like this:<\/p>\n
\r\n\r\n$posts['products'] = json_decode(json_encode($posts['products']), true);\r\n\r\n<\/pre>\nI’m aware that this method will become pretty slow when more posts and votes are added to the site, but I’m very conscious of optimising too soon. At some point I’ll look into implementing caching and perhaps a cron that auto runs the above every X minutes or something like that.<\/p>\n
Here’s the resulting sort of posts:<\/p>\n
<\/a><\/p>\nDo you know of a way I can make this better or more efficient? Let me know in the comments \ud83d\ude42<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"I’m building a directory of internet marketing products at the moment called imrepo.com. It’s a project for me to learn more complex Laravel stuff and toy around with ranking algorithms, though I think there’s actually some serious money to be made if the idea is executed well. I had a slight dilemma in that I…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[6],"tags":[27,12],"yoast_head":"\n
Implementing a 'hottest' algorithm in Laravel like that of Reddit \/ Hacker News - JoeTannorella.com<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n