所以,我正在尝试向模型添加属性(评级)。
到目前为止我这样做了:
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 以避免被零除。
关于php - Laravel lmutator $this->属性返回 'Undefined index: id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32380495/