所以,我试图添加一个属性(评级)到一个模型。
到目前为止,我这样做了:
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');
}
但是它返回Undefined index: id
奇怪的是,如果我在$this->attributes
上执行dd
,它会显示所有数组属性,包括id
。
我做错了什么,我怎么能得到属性值?
尝试利用关系并只选择聚合。
public function getRatingAttribute()
{
return $this->reviews()
->selectRaw('AVG(reviews.rating) as aggregate')
->pluck('aggregate');
}
更新:使用内置的AVG来避免除零
您可以使用内置关系来简化,这样您就不必担心手动处理属性了。
。
public function reviews()
{
$this->hasMany('App'Review');
}
public function getRatingAttribute()
{
return $this->reviews->count() > 0 ? $this->reviews->sum('rating') / $this->reviews->count() : 0;
}