My website has submissions, and those submissions have votes.
Upvotes are stored in the SubmissionVotes table as a tinyint in the column "vote" as 1
, and downvotes are stored as -1
.
In my Submission.php
model, there is a hasMany relationship to the vote model.
public function votes() {
return $this->hasMany('App\SubmissionVote', 'vote');
}
In my blade template, I calculate the sum of these votes:
{{ $submission->votes->sum('vote') }}
Now this works fine if there's only upvotes. Three upvotes will return a score of 3.
But given a 3 downvotes and 3 upvotes, the sum should return 0 However, it returns 3.
In other words, it counts -1 as 0.
Edit:
Strange development. When I view what $submission->votes
returns, it only gives me the results with positive numbers.
For example:
[{"id":13,"user_id":2,"submission_id":1,"vote":1},{"id":22,"user_id":3,"submission_id":1,"vote":1}]
but when I view the database, I can see the negative votes as well:
collect([-1, 2, -2])->sum()
the result is -1 which is correct, so make sure that you have the values as you expect them. Check what does$submission->votes
returns in your controller maybe, and see manually first if the result is what you expect. – nakov$submission->votes
it returns[{"id":13,"user_id":2,"submission_id":1,"vote":1},{"id":22,"user_id":3,"submission_id":1,"vote":1}]
etc. but it's only returning the results with vote = 1 and not the results with vote = -1 – Felix Maximevote
should not be the foreign key of the relationship. It probably works cause$submission->id
would be 1, and it's returning all records wherevote
is 1. I think the answer below is saying the same thing. – Tim Lewis