首页 > 解决方案 > 计算laravel中的平均餐厅评分

问题描述

我有一个包含以下字段的餐厅表

Schema::create('restaurants', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('name');
            $table->text('menu');
            $table->string('hours');
            $table->string('contact');
            $table->string('payment');

包括 rating_count ,它存储我稍后添加的平均评分

[我有一个评论表,其中存储了每家餐厅的评分]

https://i.stack.imgur.com/MXudX.png 我想计算每家餐厅的平均评分并将其作为数字显示在餐厅视图中

标签: javascriptjquerylaravel

解决方案


您需要在 Restaurant 模型中设置关系,如下所示:

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

然后要计算评级,您可以添加另一种方法:

public function rating()
{
    $totalReviews = $this->reviews->count();

    if($totalReviews)
    {
        $totalRating = $this->reviews->sum('rating');

        return number_format($totalRating / $totalReviews, 1);
    }

    return 0;
}

然后使用它:

$restaurant = Restaurant::find(1)->with('reviews');

$restaurant->rating(); // should give you what you need.

- 编辑

在您的 Restaurant 模型中添加这样的访问器:

protected $appends = ['rating_count'];

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

然后使用它:

$restaurant->rating_count;

推荐阅读