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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题