【问题标题】:Creating a new collection from another collection从另一个集合创建新集合
【发布时间】:2017-02-21 02:06:49
【问题描述】:

我从我所做的查询中创建特定数据的集合,但我需要创建一个新集合,其中只有一些具有自定义名称属性的数据,我使用的是数组,但我需要在集合中创建它,因为它更容易格式化数据并访问一些集合方法。

我目前的代码是这样的:

    $activity = [];
            $temp = [];

$calculations = collect($user->calculations()
            ->withTrashed()
            ->orderBy('updated_at', 'desc')
            ->get());

        foreach($calculations as $calculation){
            $temp['type'] = "calculation";
            $temp['name'] = $calculation->name;
            $user = $this->getUserById($calculation->pivot->user_id);
            $temp['user'] = $user->name ." ".$user->surname;



            if($calculation->created_at == $calculation->updated_at && $calculation->deleted_at == null)
            {
                $temp['operation'] = "saved";
                $temp['date'] = $calculation->created_at;
                $temp['diff'] =  Carbon::parse($calculation->created_at)->diffForHumans();
            }elseif($calculation->created_at != $calculation->updated_at && $calculation->deleted_at != null)
            {

                $temp['operation'] = "changed";
                $temp['date'] = $calculation->updated_at;
                $temp['diff'] =  Carbon::parse($calculation->updated_at)->diffForHumans();

            }else{
                $temp['operation'] = "delete";
                $temp['date'] = $calculation->deleted_at;
                $temp['diff'] =  Carbon::parse($calculation->deleted_at)->diffForHumans();
            }


           array_push($activity,$temp);


        }
     $conditions = collect($user->conditions()
                ->withTrashed()
                ->orderBy('updated_at', 'desc')
                ->get());


            foreach($conditions as $condition){
                $temp['type'] = "condition";
                $temp['name'] = $condition->name;
                $user = $this->getUserById($condition->user_id);
                $temp['user'] = $user->name ." ".$user->surname;

                if($condition->created_at == $condition->updated_at && $condition->deleted_at == null)
                {
                    $temp['operation'] = "saved";
                    $temp['date'] = $condition->created_at;
                    $temp['diff'] =  Carbon::parse($condition->created_at)->diffForHumans();
                }elseif($condition->created_at != $condition->updated_at && $condition->deleted_at != null)
                {

                    $temp['operation'] = "alterado";
                    $temp['date'] = $condition->updated_at;
                    $temp['diff'] =  Carbon::parse($condition->updated_at)->diffForHumans();

                }else{
                    $temp['operation'] = "delete it";
                    $temp['date'] = $condition->deleted_at;
                    $temp['diff'] =  Carbon::parse($condition->deleted_at)->diffForHumans();
                }

                array_push($activity,$temp);

我已经将 eloquent 查询转换为“收集”,但是我无法创建新的集合,我需要使用数组方法来代替,我应该使用集合方法来创建它们。

基本上我的主要原因是我需要合并“条件”和“计算”,而不是能够为集合排序数据时间。

【问题讨论】:

  • 查询构建器已经返回了结果集合,因此不需要起始collect(query...)
  • 上面的代码有什么问题?我同意@Pedro
  • 你想把$activity数组转换成collection吗?
  • @VaibhavrajRoham 没什么大不了的。我只是说他将两个查询的结果包装在collect(result) 中,这是完全不必要的,因为查询结果已经自动转换为集合。
  • 对不起@devk 我应该说我同意你的看法。抱歉打错了

标签: php laravel laravel-5 eloquent


【解决方案1】:

这样的事情怎么样。

我在集合上使用了transform 方法(为了转换键名)。我已经复制了您的逻辑,然后合并了两个集合。

$calculations = $user->calculations()
        ->withTrashed()
        ->orderBy('updated_at', 'desc')
        ->get();

$transformed = $calculations->transform(function($item, $key) use($user) {
        $toReturn = [];
        $toReturn['type'] = "calculation";
        $toReturn['name'] = $item->name;
        $toReturn['user'] = $user->name;

        if($item->created_at == $item->updated_at && $item->deleted_at == null) {
            $toReturn['operation'] = "saved";
            $toReturn['date'] = $item->created_at;
            $toReturn['diff'] =  Carbon::parse($item->created_at)->diffForHumans();
        } elseif($item->created_at != $item->updated_at && $item->deleted_at != null){
            $toReturn['operation'] = "changed";
            $toReturn['date'] = $item->updated_at;
            $toReturn['diff'] =  Carbon::parse($item->updated_at)->diffForHumans();

        } else {
            $toReturn['operation'] = "delete";
            $toReturn['date'] = $item->deleted_at;
            $toReturn['diff'] =  Carbon::parse($item->deleted_at)->diffForHumans();
        }
        return $toReturn;
    });

 $conditions = $user->conditions()
            ->withTrashed()
            ->orderBy('updated_at', 'desc')
            ->get();

$transformed2 = $conditions->transform(function($item, $key) use($user) {
        $toReturn = [];
        $toReturn['type'] = "calculation";
        $toReturn['name'] = $item->name;
        $toReturn['user'] = $this->getUserById($item->user_id);

        if($item->created_at == $item->updated_at && $item->deleted_at == null) {
            $toReturn['operation'] = "saved";
            $toReturn['date'] = $item->created_at;
            $toReturn['diff'] =  Carbon::parse($item->created_at)->diffForHumans();
        } elseif($condition->created_at != $condition->updated_at && $condition->deleted_at != null){
            $toReturn['operation'] = "changed";
            $toReturn['date'] = $item->updated_at;
            $toReturn['diff'] =  Carbon::parse($item->updated_at)->diffForHumans();

        } else {
            $toReturn['operation'] = "delete";
            $toReturn['date'] = $item->deleted_at;
            $toReturn['diff'] =  Carbon::parse($item->deleted_at)->diffForHumans();
        }
        return $toReturn
    });

$merged = $transform->merge($transform2);

【讨论】:

  • 您好,感谢您的反馈,我收到“调用数组上的成员函数 getKey()”的错误
  • 哪一行,哪个文件?
【解决方案2】:

以@devk 的回答为基础,这是一个更简洁的版本,没有太多重复的代码:

/**
 * Transform a collction with a given callback
 *
 * @param   Collection   $collection     A laravel collection
 * @param   User         $user           A User object
 * @return  Collection
 **/
private function transformCollection(Collect $collection, User $user) {
    return $collection->transform(function($item, $key) use ($user) {
        $toReturn = [
            'type' => 'calculation',
            'name' => $item->name,
            'user' => $user->name
        ];

        if ($item->created_at == $item->updated_at && $item->deleted_at == null) {
            $toReturn['operation']  = "saved";
            $toReturn['date']       = $item->created_at;
            $toReturn['diff']       = Carbon::parse($item->created_at)->diffForHumans();
        } elseif ($item->created_at != $item->updated_at && $item->deleted_at != null) {
            $toReturn['operation']  = "changed";
            $toReturn['date']       = $item->updated_at;
            $toReturn['diff']       = Carbon::parse($item->updated_at)->diffForHumans();
        } else {
            $toReturn['operation']  = "delete";
            $toReturn['date']       = $item->deleted_at;
            $toReturn['diff']       = Carbon::parse($item->deleted_at)->diffForHumans();
        }

        return $toReturn;
    });
}

// Return all user calculations ordered by when they were updated including deleted
$calculations   = $user->calculations()->withTrashed()->orderBy('updated_at', 'desc')->get();
$conditions     = $user->conditions()->withTrashed()->orderBy('updated_at', 'desc')->get();

// Transform both collections
$transformed    = transformCollection($calculations, $user);
$transformed2   = transformCollection($conditions, $user);

// Merge the resulting collections into a single collection
$merged = $transform->merge($transform2);

编辑

如果您的 Calculation 对象有一个模型,您还可以通过将日期添加到 protected $dates = [] 数组来确保将日期返回为 Carbon 日期

protected $dates = [
    'deleted_at',
    'created_at',
    'updated_at'
];

我认为 created_atupdated_at 默认包含在 BaseModel 的一部分中,我认为我很可能是错的。

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多