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 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并