douchuang1861 2017-01-10 15:17
浏览 75
已采纳

JSON文件返回带有额外字段的关联数组

I want to pass data from back end into the front end with JSON file, but instead of returning an associative any time stamp as key and values, it returns extra field from the table.

Anyone who can help me to hide extra fields?

namespace App\Http\Controllers;
use App\Notification;
use App\Status;

use Illuminate\Http\Request;

class ChartController extends Controller
{
    public  function speedHistory($notification_id){

        $o_notification = Notification::find(intval($notification_id));
        $o_status = Status::where('name','speed')->first();

        $o_response = $o_notification->statuses()->where('status_id', $o_status->id)
        ->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();

        if($o_response){
            return response()->json($o_response->toArray());
        }else{
            // return an empty json array instead of false
            //return false;
            return response()->json(array());
        }
    }
}

The return looks like this, I was expecting to get the value which is 72 in this case and the time stamp.

[{"value":"72","pivot":{"notification_id":1,"status_id":2,"values":"72","created_at":"2017-01-10 12:48:29","updated_at":"2017-01-10 12:48:29"}}]
  • 写回答

2条回答 默认 最新

  • douhan4812 2017-01-10 15:56
    关注

    This is how you get the result you want:

    $o_response = $o_notification->statuses()->where('status_id', $o_status->id)
        ->orderBy('created_at','DESC')
        ->get()
        ->transform(function ($item, $key) {
            return collect([
                'values' => $item->pivot->values,
                'created_at' => $item->pivot->created_at
            ]);
        });
    

    Then just return

    return response()->json($o_response);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵