微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel 在映射器中将 ->first() 转换为数组并与数组合并

如何解决Laravel 在映射器中将 ->first() 转换为数组并与数组合并

我的 Laravel 8 项目有一个函数一个从我的数据库获取数据的查询,我想将我的映射器中返回的 first 项转换为一个数组,以便我可以从中的值覆盖它的值我的 $stats 数组。

我该如何转换才能达到这个结果?

我需要返回包含我的数据的整个对象,而 diskSpacetotal 只是我的字段之一,我不想在这里手动写出每个对象键,因此我为什么要尝试使用第一个项目,然后用我需要的内容覆盖:

/**
 * Get average history
 */
public function getAverageHistory($agent,$from)
{

  $history = DB::table('data_profiler_agents')
              ->where('agent',$agent)
              ->join('data_profiler_agents_history',function ($join) use (&$from) {
                  $join->on('data_profiler_agents.id','=','data_profiler_agents_history.agent_id')
                       ->where('data_profiler_agents_history.created_at','>=',$from)
                       ->where('data_profiler_agents_history.created_at','<=',Carbon::Now())
                       ->orderBy('created_at','asc');
              })
              ->get();

  $history = $history->groupBy(function($reg) {
    $date = Carbon::parse($reg->created_at);
    return $date->format('Y-m-d H:00:00');
  });

  $history = $history->map(function ($item,$key) {
    $stats = [
      'diskSpacetotal' => $item->sum('diskSpacetotal')
    ];

    // this part can't be converted to an Array,what's the workaround
    return array_merge($item->first()->toArray(),$stats);
  });

  return $history;

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。