只检索必要的数据

Retrieve only necessary data

这是我的商店功能

public function store(Request $request)
{
    $post = new Post();
    $post->author()->associate(auth()->user());
    $post->fill($request->all());
    $post->save();

    return response()->json($post);
}

作为回应我得到:

我不想要所有数据,所以我尝试只获取我这样定义的数据:

$post = $post->only([
    'id',
    'title',
    'content',
    'published_at',
    'author'
]);

现在的响应是:

好多了,但还不完全。我无法以这种方式定义 post 作者数据。 唯一的方法是创建一个令人毛骨悚然的关系,您 select 只有必要的数据或像这样:

    $post = [
        'id' => $post->id,
        'title' => $post->title,
        'content' => $post->content,
        'published_at' => $post->published_at->toDateTimeString(),
        'author' => [
            'id' => $post->author->id,
            'name' => $post->author->name,
            'email' => $post->author->email,
        ]
    ];

所以我的问题是......也许有更优雅的方法来实现这一点。

非常感谢!

我会为您的 Post 模型添加一个功能

public function jsonOutput()
{
    $array['id'] = $this->id;
    $array['title'] = $this->title;
    $array['content'] = $this->content;
    $array['author'] = [
        'id' => $this->author->id,
        'name' => $this->author->id
    ];

    return $array;
}

然后这样称呼它

return response()->json($post->jsonOutput());

最简单的方法可能是只对作者使用 only

return $post->only('id', 'title', 'content') + [
        'author' => $post->author->only('id', 'name', 'email'),
    ];

如果它会变得更复杂或在其他地方重复使用,那么我建议使用类似 Eloquent Resources

的东西