I have three models:
- Product
- Review
- Score
They are linked like this:
- Product (hasMany) -> Review (hasOne) -> Score
Review model:
- text
- product_id
- score_id
Score model:
- value (number)
My relation in Product model:
public function reviews () {
return $this->hasMany(Review::class, 'product_id', 'id');
}
public function averageScore () {
// ???
}
I need to calculate average product score (by score.value prop), but have no idea how to achieve it.
2
Answers
Two routes you can go the pure
SQL
approach or you can useEloquent
to eager load it and calculate it. The last solution avoids N+1 problems the best but sometimesSQL
only solutions can be beneficial, that you don’t have to iterate over as many models.Eloquent solution
Here you have to iterate over most of the relationships, but everything is eager loaded. Doing this for multiple will produce minimal
SQL
queries.SQL solution
If you iterate over this, it will create N queries. Is pretty efficient when only called once.
You can do this function by collection or by the query builder both
The collection approach is
The query bilder approach is below
However the query builder approach is more optimized. You may use one as per your use case.