我有一张包含以下字段的餐厅表
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,它存储我后来添加的平均评分
[我有一个评论表,其中存储了每家餐厅的评分]
/image/MXudX.png 我想计算每家餐厅的平均评分并将其显示在餐厅 View 中作为数字
最佳答案
在餐厅模型中,最好让定义关系的方法尽可能简单。
public function reviews() {
return $this->hasMany('App\Review');
}
现在您可以使用此关系来获取比率,您可以在模型中添加一个不是列的属性作为附加属性。
protected $appends = ['rate'];
然后有一个函数来赋值:
public functions getRateAttribute() {
return $this->reviews->avg('rate') ?? 0;
}
问题是,顾名思义,附加属性总是附加到模型的实例上。
因此,如果您只执行以下操作:
$restaurant= Restaurant::first();
即使你不需要费率,laravel 仍然会为你准备好 $restaurant->rate
,因此它会执行平均查询。
还有 Laravel 的 avg('column_name')
:
- 没有数据时返回null
- 如果对非数字列取平均值,它给出的值类似于 0.0
- 如果存在的值超过 2 个小数点(主要是 4 个),则以 3.9265 格式给出有效值
关于javascript - 计算 laravel 中餐厅的平均评分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57112090/