TicketResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'user_id' => $this->user_id,
'title' => $this->title,
'body' => $this->body,
'status' => $this->status,
'created_at' => $this->created_at->toDateTimeString(),
];
}
CommentResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'body' => $this->body,
'user_id' => $this->user_id,
'created_at' => $this->created_at->toDateTimeString()
];
}
TicketController.php
public function index()
{
return TicketResource::collection(Ticket::all());
}
public function show(Ticket $id)
{
$ticket = $id;
return new TicketResource($ticket);
}
Model Ticket.php
public function comments()
{
return $this->hasMany('App\Comment');
}
Model Comment.php
public function ticket()
{
return $this->belongsTo('App\Ticket');
}
routes / api.php
Route::get('tickets', 'TicketController@index');
Route::get('tickets/{id}', 'TicketController@show');
我希望在请求tickets/{id}
网址时收到此响应:
{
"data": {
"id": 1,
"user_id": 2,
"title": "lorem",
"body": "epsum",
"status": "open",
"created_at": "2020-03-04 18:14:56",
"comments": [
{
"id": 1,
"body": "equi",
"user_id": 1,
"created_at": "2020-03-05 18:14:56",
}
]
}
}
相反,当我访问tickets
网址时,我不想在每张票证上都添加comments
。
我该如何实施?
您需要添加关系
您需要load
您的关系。