1

I have been having trouble writing an Eloquent query that finds my post with the most votes. I have a votes table and a posts table. The votes table has an id column, a post_id column, a user_id column, and a vote column. If someone votes for a post the vote column is set to the value of 1. If someone downvotes a post the vote column is set to 0. I can find the amount of votes for one post by using the following query:

Vote::where('post_id','=', $post->id)->where('vote','=',1)->count()

How could I improve upon this query to find the posts with the most votes? I have tried coming up with a method and I just can't seem to do it. Thanks so much.

user2094178
  • 9,204
  • 10
  • 41
  • 70
codeforfood
  • 429
  • 9
  • 28
  • Have you considered adding an `orderBy()` to your Eloquent query? [laravel 4 how to order by using eloquent orm](http://stackoverflow.com/questions/17553181/laravel-4-how-to-order-by-using-eloquent-orm) – Mark Baker Jun 29 '14 at 20:53
  • This is what you want http://stackoverflow.com/questions/24418176/order-by-votes-in-laravel-orm/24419654#24419654 – Jarek Tkaczyk Jun 30 '14 at 11:37

1 Answers1

2

Just do....

DB::table('votes')->orderBy(DB::raw('sum(\'vote\')'))
                ->groupBy('post_id')->get();

This will order your votes, by their SUM

Kylie
  • 11,421
  • 11
  • 47
  • 78
  • Thanks, but I'm trying to order the posts by the amount of votes. Could this do that for me? I want to be able to return the posts title, and body and other things like that. – codeforfood Jun 29 '14 at 22:06
  • 1
    Well then all you gotta do Vote::where('post_id','=', $post->id)->orderBy('vote')->get() If the above comment is actually what you want (all posts ordered by vote) But your original question seems to say you wanted to find the post with most votes. – Kylie Jun 30 '14 at 00:42