php - Laravel lmutator $this->属性返回 'Undefined index: id'

标签 php laravel eloquent

所以,我正在尝试向模型添加属性(评级)。

到目前为止我这样做了:

    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/

相关文章:

php - 使用正则表达式解析方括号

php - Laravel 5 将模型事件设置为模型删除时的 "clear up"数据透视表

php - 数据库结构 : Multiple tables with common ID

php - Carbon 'InvalidArgumentException' 覆盖 $dateFormat 属性时消息为 'Trailing data'

mysql - Laravel 4 将数据库字段更新为空 - 错误

php - laravel 中错误的时间戳

javascript - 如何记住 NAV 的滚动位置(固定/溢出-y :scroll)

php - 找不到实体存储库方法

database - Laravel - 如何制作一个将列添加到数据库表的按钮

javascript - 在 wordpress 中使用 jquery 日期选择器