【问题标题】:how to access multiple array elements in blade file laravel如何访问刀片文件laravel中的多个数组元素
【发布时间】:2020-08-08 11:42:31
【问题描述】:

评级模型

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');
    }
}

RatingController

public function index()
{

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

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

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

中的元素

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

【问题讨论】:

  • ratings 是一个数组,你应该通过调用它的索引或另一个foreach来检索元素

标签: arrays laravel object eloquent-relationship


【解决方案1】:

据我了解,您希望获得平均评分。

在您的 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

}

在你的刀片文件中,你可以简单地做

$toilet->getAverageRating()

这将给出平均评分。

【讨论】:

  • 这很好用,但新注册的厕所面临除以 0 异常.. 所以补充说:if ($count>0) return $total_ratings / $count; // average else return 0;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 2019-05-08
  • 2020-08-17
  • 2016-10-13
  • 1970-01-01
  • 2019-07-29
  • 2017-08-19
相关资源
最近更新 更多