M
M
maaestr02022-03-15 17:03:20
Laravel
maaestr0, 2022-03-15 17:03:20

How to do it correctly (laravel)?

Hello. The database contains tables products and reviews. There is a rating row in the reviews table (from 1 to 5). For each product, you need to display its rating. I do the following.
In the "Products" model

public function reviews()
    {
        return $this->hasMany(CourseReviews::class);
    }

 public function getAvgRating(){
        return round($this->reviews->pluck('rating')->avg());
    }


In template
<span class="star ">{{$course->getAvgRating()}}</span>

But in one of the articles I read that this is a bad form when you access the database from the template. Tell me how best to do it. I would be grateful for any advice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2022-03-15
@JhaoDa

Documentation is your best friend!

A
Anton Anton, 2022-03-15
@Fragster

Considering that adding a review with a rating is much less frequent than an impression, it is logical to make an additional column in the product table or in a separate 1 to 1 linked table with frequently changed data, in which to recalculate this value when adding a review.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question