我想使用JSON文件将数据从后端传递到前端,但不是将任何时间戳作为键和值返回关联,而是从表中返回额外的字段。
任何可以帮我隐藏额外字段的人都会?
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());
}
}
}
返回看起来像这样,我希望在这种情况下获得72的值和时间戳。
[{"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"}}]
答案 0 :(得分:0)
该关系将返回Laravel Collection,因此您可以使用only 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()
->only(['value', 'created_at']);
<强>更新强>
如果集合中有多个结果,则上述答案将无效。在这种情况下,您可以使用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
];
});
答案 1 :(得分:0)
这就是你得到你想要的结果的方法:
$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
]);
});
然后返回
return response()->json($o_response);