【问题标题】:Laravel: Sum Collection by Custom MethodLaravel:通过自定义方法收集总和
【发布时间】:2015-05-27 04:42:39
【问题描述】:

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

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

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

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

但似乎 laravel 只会按实际字段求和,而不是自定义方法。例如,这会起作用:

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

关于如何进行这项工作的任何想法?

【问题讨论】:

  • 如果您希望将 custommethodtest 作为自定义表字段名(属性)返回,那么您可以定义访问器
  • 我们需要反馈。 :)

标签: php laravel-4 eloquent


【解决方案1】:

创建一个attribute accessor,而不只是一个方法:

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

然后:

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

【讨论】:

    【解决方案2】:

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

    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);
    }
    

    出于这个原因:

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

    【讨论】:

    • 如果数组和 JSON 表示中不需要该属性,则附加它没有任何好处。这由 OP 来决定。这不是“更好”
    • 在属性访问器中设置属性也是不必要的。会自动缓存
    • @lukasgeiter 先生,您说得对,如果数组和 JSON 中不需要它,但我相信在这种情况下 custom_test 应该像建议的问题一样被视为字段名,而不仅仅是一种方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2014-08-25
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多