条件Laravel资源



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('AppComment');
}

模型注释.php

public function ticket() {
return $this->belongsTo('AppTicket');
}

路由/api.php

Route::get('tickets', 'TicketController@index');
Route::get('tickets/{id}', 'TicketController@show');

我想当我请求tickets/{id}URL时,我希望收到这个响应:

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

相反,当我访问ticketsURL时,我不希望在每张票上添加comments

我该如何实现?

您需要添加关系

这是我的模型类:

<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Category extends Model
{
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id')->select('categories.id', 
'categories.cid AS key', 
'categories.name AS label', 
'categories.type',
'categories.lvl');
}
}

在我的控制器中:

$parents = Category::select(
'categories.id', 
'categories.id AS key', 
'categories.name AS label')->where('lvl', 1)->get();
foreach ($parents as $item) {
$item->children
}
return Response::json($parents, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);

结果:

[
{
"id":2,
"key":2,
"label":"parent label",
"children":[
{
"id":17,
"key":"92697f63-5c50-11ea-80df-5cf9ddf839d3",
"label":"child label",
"type":"Category",
"lvl":2,
}
]
}
]

最新更新