试图在Laravel创建一个五星评级系统。星率是一个在[1-5]范围内的浮点数,它成功地存储在数据库中。数据库中费率表的迁移文件。(我已经将星形列的数据类型设置为浮动(
public function up()
{
Schema::create('rates', function (Blueprint $table) {
$table->id();
$table->morphs('rateble'); //creates rateable_id and rateable_type
$table->foreignId('user_id')->nullable()->constrained()->onUpdate('cascade')->onDelete('set null');
$table->float('star',2, 1); //star number is from 0 to 5
$table->timestamps();
});
}
然后,为了对特定产品的评级进行平均,我使用了以下查询:
public function scopeAverageRate($query, $type, $id)
{
return $query->where('rateble_type', $type)
->where('rateble_id', $id)
->avg('star');
}
问题是,似乎avg()
方法将结果强制转换为integer!有什么方法可以设置这个函数来处理浮点数吗?
例如,假设一个特定产品只有一个等于"0.5"星的评级,那么平均评级是"0"而不是"0.5"!
我该如何解决这个问题?
提前谢谢你,
正确的答案是为平均函数编写原始sql,如:
->selectRaw('CAST(AVG(star) AS DECIMAL(2,1)) AS star_avg')->first()->star_avg;
请注意,star
是一列的名称,我们希望对其进行平均值。
更多信息:点击这里