【问题标题】:Laravel collection - filter() method setting custom propertyLaravel 集合 - filter() 方法设置自定义属性
【发布时间】:2020-03-22 20:46:57
【问题描述】:

我创建了一个自定义集合类,它扩展了 laravel 集合类。这个自定义集合具有一些特定于数据的处理方法和一个属性,可以让我的生活更轻松。

use Illuminate\Support\Collection;

class CustomCollection extends Collection
{
    public bool $myProperty = true;

    public function filterBasedOnCustomStuff()
    {
        return $this->filter(function ($row)
        {
            // Some custom sorcerry
            return ($var === "whatever");
        });
    }
}

我的问题是。当我调用 filterBasedOnCustomStuff() 方法时,它返回一个新的 CustomCollection 对象。这当然是我想要的。但我还想设置新集合实例的$myProperty 参数的值。有可能还是我必须在之后的实例上这样做?有这样的想法:

$newCollection = $oldCollection->filterBasedOnCustomStuff();
$newCollection->myProperty = $oldCollection->myProperty;

如果可能的话,我想避免这种事后设置的方法。

提前谢谢你。

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    我会简单地使用一个变量来保存过滤后的实例:

    <?php
    use Illuminate\Support\Collection;
    
    class CustomCollection extends Collection
    {
        public bool $myProperty = true;
    
        public function filterBasedOnCustomStuff()
        {
            $filtered = $this->filter(function ($row)
            {
                // Some custom sorcerry
                return ($var === "whatever");
            });
    
            $filtered->myProperty = $this->myProperty;
    
            return $filtered;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2013-01-25
      • 2012-12-17
      相关资源
      最近更新 更多