【问题标题】:Laravel API - Vue.js returning Posts with userLaravel API - Vue.js 与用户一起返回帖子
【发布时间】:2017-01-24 13:38:02
【问题描述】:

我正在尝试学习使用 Laravel 构建的 API 的 Vue.js。这个想法很简单,一个用户可以发一个帖子,一个帖子可以有 cmets。我可以让关系在 laravel 中工作,但我不知道如何使用 Vue.js 返回帖子的作者姓名或评论。

当使用刀片模板引擎时,我在 foreach 循环中使用类似的东西来返回作者姓名:

{{ $post->user->name }}

当我通过 API 返回帖子时,除了用户 ID 外,我没有获得任何用户信息。如何获取属于该帖子的用户信息?

{
  "message": "Success",
  "data": [
    {
      "id": 1,
      "body": "test body 1",
      "user_id": "1",
      "created_at": "2016-09-16 10:22:57",
      "updated_at": "2016-09-16 10:22:57"
    }
  ]
}

<script>
  export default {
        /*
         * The component's data.
         */
         data() {
            return {

                posts: [],

            };
        },

        /**
         * Prepare the component.
         */
         ready() {

            this.getPosts();

        },

        methods: {

            /**
             * Get Posts.
             */
            getPosts: function() {
                this.$http.get('/api/wall/posts')
                    .then(response => {

                        this.posts = response.data.posts;

                    });
            }

        }
    }
</script>

public function getPosts($id = null)
    {
        if (!$id){
            $data = Post::all();
            $message = 'Success';
            $code = 200;
        } else {
            $data = Post::FindOrFail($id);
            $message = 'Success';
            $code = 200;
        }
        return Response::json(['message' => $message, 'data' => $data], $code);
    }

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    您可以为此使用预先加载:

    Post::with('user')->FindOrFail($id);
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2017-03-18
      • 2017-04-03
      • 2016-07-16
      • 2020-06-07
      • 2019-04-24
      • 1970-01-01
      • 2020-12-11
      • 2020-12-05
      相关资源
      最近更新 更多