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 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关
  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏