Laravel lmutator $ this->属性返回'Undefined index:id' [英] Laravel lmutator $this->attributes return 'Undefined index: id'
本文介绍了Laravel lmutator $ this->属性返回'Undefined index:id'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我做到了这一点:
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');
}
但它返回未定义的索引:id
奇怪的是,如果我在 $ this-上执行
它显示所有数组属性,包括 dd
>属性 id
。
我是什么做错了,如何获取属性值?
解决方案
尝试利用关系,只需选择聚合。
public function getRatingAttribute()
{
return $ this-> reviews()
- > selectRaw('AVG(reviews.rating)as aggregate')
- > pluck('aggregate');
}
更新:更改为使用内置AVG避免除以零。
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.
这篇关于Laravel lmutator $ this->属性返回'Undefined index:id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文