如何访问 blade 文件 laravel 中的多个数组元素

how to access multiple array elements in blade file laravel

评分型号

class Rating extends Model
{
    protected $fillable = [
        'owner_id', 'toilet_id','user_id','rating','desc',
    ];

    public function toilet()
    {
        return $this->belongsTo(ToiletInfo::class);
    }
}

厕所信息型号

class ToiletInfo extends Model
{
    protected $fillable = [
        'owner_id', 'toilet_name','price','complex_name','address','toilet_lat','toilet_lng','status',
    ];

    public function owner()
    {
        return $this->belongsTo(ToiletOwner::class);
    }

    public function ratings()
    {
        return $this->hasMany(Rating::class,'toilet_id');
    }
}

评级控制器

public function index()
{

    return $toilets = ToiletInfo::with('ratings')->get();

    //return view('admin.rating',compact('toilets'));
}

我想获得 rating 的平均值,但如何访问 ratings[]

中的元素

或者帮助我改进我用来获取用户评论的厕所评级的方法

根据我从你的问题中了解到你希望获得平均评分。

在您的 ToiletInfo 模型中,添加一个新方法:

public function getAverageRating()
{
    $ratings = $this->ratings;
    $count = $ratings->count(); // total count
    $total_ratings = $ratings->sum('rating'); // add the 'rating' for all rows
    return $total_ratings / $count; // average

}

在您的 blade 文件中,您只需执行

$toilet->getAverageRating()

这将给出平均评分。