I have a table called jokes and a table called votes. jokes has many votes. On my vote table I have an attribut called vote. vote can be either 1 or 0. 1 for up vote and 0 for down vote. In my system I want to let the user filter to se the most voted jokes. My question is how can I order my jokes with most up votes.
For a single joke I get the its up votes count like this:
$vote_up_count = $joke->votes()->where('vote', '=', 1)->count();
But I have no clue how to OrderBy relationship count where vote in votes = 1.
This may be a long way to do it but it should work:
Step 1: Get a collection of jokes $jokes
.
Step 2: Iterate over the jokes collection to get the income relationship model $jokes->each(function ($joke){});
.
Step 3: For each votes relationship get the amount of votes equal to 1 by filtering only the votes that have vote == 1
. $joke->votes->filter(function ($vote) {return ($vote->vote == 1);})->count()
.
Step 4: Add a count of votes property to the jokes model $joke->count = $count
.
Step 5: Order the entire jokes collection in descending order on the new count property sortByDesc('count')
.
Final result looks something like this:
$sortedByVoteCount = ($jokes->each(function ($joke) {
$count = ($joke->votes->filter(function ($vote) {
return ($vote->vote == 1);
})->count());
$joke->count = $count;
})->sortByDesc('count'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.