Steve
Steve

Reputation: 1672

Getting the sum of numbers

Answer has many rates:

Answer Model:

public function rates()
{
    return $this->hasMany('App\Rate'); 
}

Rates table:

id answer_id user_id  rating
1   3          1       5
2   3          2       8

How do i get the specific answer with sum of rating?

Upvotes: 2

Views: 92

Answers (1)

Vineeth  Vijayan
Vineeth Vijayan

Reputation: 1275

From your question, you have two classes Answer and Rate. Also, there is hasMany relationship from Answer to Rate named 'rates'.

So for the sum of ratings of a specific answer, you can call 'sum' method from 'rates' relationship on 'Answer' model.

$answer          = App\Answer::find(1);
$sum_of_rating   = $answer->rates->sum('rating');

Upvotes: 1

Related Questions