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"}}]

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);

The relation will return a Laravel Collection, so you can use the only function to only get the keys you need.

Like so:

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

Update:

The answer above will not work if there are multiple results in the set. In this case, you can use the map function.

$o_response = $o_notification->statuses()
    ->where('status_id', $o_status->id)
    ->select('values AS value', 'created_at AS timestamp')
    ->orderBy('created_at','DESC')
    ->get()
    ->map(function ($v) {
        return [
            'value' => $v->value,
            'created_at' => $v->created_at
        ];
    });