为了账号安全,请及时绑定邮箱和手机立即绑定

在 Laravel 中映射数据

在 Laravel 中映射数据

PHP
慕沐林林 2022-11-04 17:29:52
我无法理解 Laravel 中 API 的响应,这令人困惑。我期待这个输出{  "month": "January",  "year": 2020,  "history_data": [    {      "id": 27,      "jurnal_id": 12313,      "name": "Transaksi RAHN FLEKSI",      "point": 500,      "status": "SUKSES",      "created_at": "2020-03-18 17:03:26",      "updated_at": "2020-03-18 17:03:26",    },  ]},{  "month": "February",  "year": 2020,  "history_data": [    {      "id": 27,      "jurnal_id": 1231313,      "name": "Transaksi RAHN FLEKSI",      "point": 500,      "status": "SUKSES",      "created_at": "2020-03-18 17:03:26",      "updated_at": "2020-03-18 17:03:26",    }  ],  {    "month": "February",    "year": 2021,    "history_data": [      {        "id": 182,        "jurnal_id": 13213,        "name": "Transaksi RAHN FLEKSI",        "point": 500,        "status": "SUKSES",        "created_at": "2021-02-18 17:03:26",        "updated_at": "2021-02-18 17:03:26",      },      {        "id": 1812313,        "jurnal_id": 12313313,        "name": "Transaksi RAHN FLEKSI",        "point": 500,        "status": "SUKSES",        "created_at": "2021-02-18 17:03:26",        "updated_at": "2021-02-18 17:03:26",      }    ]    {    "month": "March",    "year": 2021,    "history_data": [        {        "id": 183,        "jurnal_id": 132313,        "name": "Transaksi RAHN FLEKSI",        "point": 500,        "status": "SUKSES",        "created_at": "2021-03-18 17:03:26",        "updated_at": "2021-03-18 17:03:26",        }    ]}如果我没记错的话,“history_data”按年和月分组。但是,我仍然得到如下回复
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

问题是 :


$makeToCollection = collect($arr)->groupBy('year');

该groupBy方法按给定键对集合的项目进行分组


只需使用:


$makeToCollection = collect($arr);

顺便说一句,collection 允许你链接它的方法来执行流畅的映射和减少:


$historyPoints = $this->historyPoint

    ->select(

        DB::raw("REGEXP_REPLACE(to_char(created_at, 'Month'), '\s+$', '') as month"),

        DB::raw("date_part('Year', created_at) as year")

    )

    ->groupBy('year', 'month')

    ->orderBy('year', 'desc')

    ->get();


/***** Here we go *****/


$makeToCollection = $historyPoints->map(function ($item) {

    $history_data = [];


    foreach (HistoryPointAdd::all() as $data) {

        $month = date('F', strtotime($data->created_at));

        $year  = date('Y', strtotime($data->created_at));


        if ($month == $historyPoint->month && $year == $historyPoint->year) {

            $history_data[] = $data;

        }

    }


    $item['history_data'] = $history_data;


    return $item;

});


return $this->sendSuccess($this->successMessage, $makeToCollection);


查看完整回答
反对 回复 2022-11-04
  • 1 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信