Laravel lmutator $ this-> attributes返回'Undefined index:id'

So, I'm trying to add an attribute (rating) to a model.

So far I did this:

    public function getRatingAttribute()
    {

        return $this::join('reviews', 'accounts.id', '=' , 'reviews.account_id')
        ->where('accounts.id', $this->attributes['id'])
        ->select(DB::raw('SUM(reviews.rating) / COUNT(reviews.id)'))->pluck('rating');
    }

But it returns Undefined index: id

The strange is if I do a dd on $this->attributes it shows all array attributes, including id.

What am I doing wrong and how can I get the attribute value?

Try leveraging the relation and just select the aggregate.

public function getRatingAttribute()
{

    return $this->reviews()
        ->selectRaw('AVG(reviews.rating) as aggregate')
        ->pluck('aggregate');

}

Update: Changed this to use the built in AVG to avoid the divide by zero.

You could simplify using built-in relationships, then you don't have to worry about handling the attributes manually.

e.g.

public function reviews()
{
    $this->hasMany('App\Review');
}

public function getRatingAttribute()
{
    return $this->reviews->count() > 0 ? $this->reviews->sum('rating') / $this->reviews->count() : 0;
}