php - Laravel 5 orderBy relationship count and pagination -


im working on link sharing website , need order links votes.

i have 'links' table , link_votes table.

the link_votes table has 'link_id' reference field links table 'id' field.

i have hasmany relationship in link model:

public function votes() {     return $this->hasmany('\app\linkvote'); } 

this returns rows (each row single vote) int link_votes table.

my standard query links , order them date created is:

$links = link::withcount('votes')->orderby('votes_count', 'desc')->paginate(10);  

what wish order links amount of votes have.

what have is:

$links = link::orderby('created_at', 'desc')->with('votes')->paginate(20); 

this works, well. have 2 types of vote in link_votes table having vote_type field. if vote upvote type of 1 if downvote type of 2.

the issue here ordering vote count taking votes count , putting votes negative vote above links don't have votes.

i need find way of ordering sum of upvotes (vote_type = 1) minus downvotes (vote_type = 2).

in view show vote count doing maths.

a change of logic allowed me easier first thought.

all needed count positive (upvotes) count order ones matter.

to have changed withcount to:

$links = link::withcount([         'votes' => function ($query) {             $query->where('vote_type', 1);         }     ])     ->orderby('votes_count', 'desc')     ->paginate(10); 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -