0
votes

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: enter image description here

1
If you try this: 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
Really strange! When I view $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 = -1Felix Maxime
and in your database you can see all the records? How do you query the records?nakov
@nakov Yes. I edited the main post to reflect thisFelix Maxime
vote should not be the foreign key of the relationship. It probably works cause $submission->id would be 1, and it's returning all records where vote is 1. I think the answer below is saying the same thing.Tim Lewis

1 Answers

2
votes

I think that your problem might be here:

public function votes() {
    return $this->hasMany('App\SubmissionVote', 'vote');
}   

vote is not a foreign key, it just happened to work for this two, because the vote is 1 and the submission is 1 I guess. But for negative number it won't work.

So instead of vote which cannot be a foreign key, you might want to change that to submission_id instead, so this:

public function votes() {
    return $this->hasMany('App\SubmissionVote', 'submission_id');
}

And in the SubmissionVote model you will have:

public function submission() {
    return $this->belongsTo('App\Submission');
}