【问题标题】:Retrieve only necessary data仅检索必要的数据
【发布时间】:2019-02-04 00:52:48
【问题描述】:

这是我的商店功能

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 = [
        '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,
        ]
    ];

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

非常感谢!

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • Laravel 5.6....

标签: json laravel api collections response


【解决方案1】:

我会在你的 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());

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-05-12
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 2012-06-13
      • 1970-01-01
      相关资源
      最近更新 更多