Laravel 5 > orderBy difference between up and down votes > pagination -
assumed i´ve got following db setup
users table
id name
posts table
id post
votes table
id user_id post_id vote (1 = up, -1 = down)
... , let´s assume i´ve setup every one-to-many relationship correctly :)
how query top 5 posts measured difference between it´s , down votes?
something great ...
$posts = post::wherehas('votes', function($query) { $query->orderbyraw('sum(\'vote\'), desc'); })->get();
... , i`d paginate later on.
now working :)
$posts = post::has('votes') ->leftjoin('votes', 'votes.post_id', '=', 'posts.id') ->selectraw('posts.*, sum(votes.vote) votes_sum') ->groupby('posts.id') ->orderby('votes_sum', 'desc') ->paginate(5);
Comments
Post a Comment