如何优化此数据结构?

时间:2017-04-05 07:05:40

标签: php laravel

API结果:

API result

php laravel

重复了article_user和article_title。

我使用变换器来转换我的数据。

  public function transform(ArticleComment $comments)
  {
    $articleInfo = $comments->article;
    $user = UserInfo::select('real_name')->find($articleInfo->created_user_id);

    return [
        'article_user'             => $user->real_name,
        'article_title'            => $articleInfo->title,
        'is_evaluator'             => $comments->is_evaluation,
        'comment_created_user'     => $comments->user,
        'created_at'               => $comments->created_at,
        'comment_content'          => $comments->content,
        'replied_comment'          => $comments->reply,
        'replied_user'             => $comments->repliedUser,
      ];
  }
}

我想要这样

article_info:{
  article_user: "",
  article_title: "",
}
article_comment:{
  content: "",
  is_evaluator: 0,
  ...
}

如何优化它? 我该怎么办?

the response

1 个答案:

答案 0 :(得分:0)

您可以使用简单数组格式化响应。在你的情况下应该是:

public function transform(ArticleComment $comments)
{
    $articleInfo = $comments->article;
    $user = UserInfo::select('real_name')->find($articleInfo->created_user_id);

    return [
        'article_info'    => [
            'article_user'  => $user->real_name,
            'article_title' => $articleInfo->title
        ],
        'article_comment' => [
            'is_evaluator'         => $comments->is_evaluation,
            'comment_created_user' => $comments->user,
            'created_at'           => $comments->created_at,
            'comment_content'      => $comments->content,
            'replied_comment'      => $comments->reply,
            'replied_user'         => $comments->repliedUser
        ]
    ];
}