【发布时间】:2020-01-29 18:27:27
【问题描述】:
我有一个结束 API 点
users/{user}
现在在用户资源中,我想返回
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
// 'comments' => $this->post->comments->keyBy('post_id')
'comments' => new CommentCollection($this->post->comments->keyBy->post_id)
];
}
CommentCollection 类
public function toArray($request)
{
// return parent::toArray($request);
return [
'data' => $this->collection->transform(function($comment){
return [
'id' => $comment->id,
'comment' => $comment->comment,
];
}),
];
}
但结果不会包含 post_id 作为键,我怎样才能让它返回具有键 post_id 的 cmets 集合?
更新
use App\models\Post;
use App\Http\Resources\Postas PostResource;
Route::get('/posts', function () {
return PostResource::collection(Post::all()->keyBy->slug);
});
这工作正常,但如果我将用户资源中的帖子集合用作关系,它就不起作用!这就是我对 cmets 收藏的要求。
【问题讨论】:
标签: php laravel laravel-5 eloquent laravel-resource