【问题标题】:Laravel Vue - Get Eloquent on json responseLaravel Vue - 在 json 响应中获得 Eloquent
【发布时间】:2019-11-16 19:34:47
【问题描述】:

我正在尝试构建一个基本的 Laravel Vue 评论系统来学习两者。

现在我正在尝试在特定的帖子文章上显示所有 cmets。

我的控制器返回 json_response。

public function comments(Post $post)
{
    return response()->json(
        $post->comments
    );
}

一切正常,我使用 Axios get 方法得到以下 json 响应。

[
  {
    "id":1,
    "post_id":1,
    "user_id":1,
    "body":"Post Comment 1",
    "created_at":null,
    "updated_at":null,
    "deleted_at":null
  },
  {
    "id":2,
    "post_id":1,
    "user_id":1,
    "body":"Post comment 2",
    "created_at":null,
    "updated_at":null,
    "deleted_at":null
  }
]

我正在使用 Vue 显示所有数据,但我不确定如何在 CommentsUsers 模型上获得 hte 雄辩的关系。

在 Blade 中,如果我将响应作为数据返回到 View 中,我可以显示用户,如下所示:

@foreach($post->comments as $comment)

   {{ $comment->user->username }}

@endforeach

如何在我的 json 响应中传递用户与 cmets 的关系,以从 user_id 值获取评论的用户?

【问题讨论】:

    标签: php json laravel vue.js axios


    【解决方案1】:

    我在 Laracasts 的帮助下设法解决了问题。

    我必须改变我的回应

    public function comments(Post $post)
    {
        return response()->json(
            $post->comments->load('user');
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2020-06-10
      • 2019-06-10
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多