javascript - 计算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 我想计算每家餐厅的平均评分并将其作为数字显示在餐厅视图中
解决方案
您需要在 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;
推荐阅读
- smtp - 通过 Microsoft Exchange Server 使用 Pentaho 发送邮件
- r - 如何在 r 的函数中使用数据框
- php - 如何配置 laravel 5 和 gclid
- c# - “System.Runtime,版本=4.2.1.0,文化=中性,PublicKeyToken=b03f5f7f11d50a3a”无法加载
- vue.js - 无法在父组件上监听子组件发出的事件
- python - 用于监控程序和控制微控制器的 Python 脚本
- nginx - Nginx 只允许我的域访问视频 url
- android - Android studio 3.5:logcat 不显示任何日志
- c++ - 为什么这里会出现“使用未初始化的内存'猜测'”?
- php - 从 div A 获取 iframe 并将其显示在 div B 中?