仅检索必要的数据

时间:2018-08-29 09:23:42

标签: json laravel api collections response

这是我的商店功能

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

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

作为回应,我得到:

enter image description here

我不想要所有数据,所以我尝试仅采用这样定义的数据:

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

现在的响应是:

enter image description here

好多了,但还不完全。我不能以这种方式定义作者后的数据。 唯一的方法是创建一个令人毛骨悚然的关系,在其中您仅选择必要的数据或像这样:

    $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,
        ]
    ];

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

非常感谢您!

2 个答案:

答案 0 :(得分:2)

最简单的方法可能就是与作者一起使用only

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

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

答案 1 :(得分:1)

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

JSON.stringify(data)

然后这样称呼它

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;
}