Laravel:通过自定义方法收集总和


Laravel: Sum Collection by Custom Method

我有一个模型,它有一个自定义方法(假设它有一个名为'fieldname'的字段)例如

class X extends 'Eloquent 
{
    function custommethodtest()
       {
           return rand(1);
       }
}

我想通过自定义方法使用集合和SUM,即:

 X:all()->sum('custommethodtest');

,但laravel似乎只会按实际字段求和,而不是自定义方法。例如,可以这样做:

X::all()->sum('fieldname');

关于如何使这个工作有什么想法吗?

不只是一个方法,而是创建一个属性访问器:

public function getCustommethodtestAttribute(){
    return rand();
}

然后:

X:all()->sum('custommethodtest');

您可以使用自定义属性来达到相同的结果;

class X extends 'Eloquent 
{
    protected $appends = [
        'custom_test'
    ];
    public function getCustomTestAttribute()
    {
        //NB: rand() expects exactly 2 parameters, am using 1234 for parameter 2 just for testing sake
        return $this->attributes['custom_test'] = rand(1,1234);
    }
}

:

X:all()->sum('custom_test');

以上方法优于只使用:

public function getCustomTestAttribute(){
  return rand(1);
}

For this reason:

一旦属性被添加到追加列表中,它将被删除包含在模型的数组和JSON表单中。属性中的的可见和隐藏配置模型。