2016-09-16 43 views
1

我想学习Vue.js,它使用Laravel来构建API构建。这个想法很简单,用户可以发表帖子,帖子可以发表评论。我可以在laravel中获得关系,但我无法弄清楚如何使用Vue.js返回帖子或评论的作者姓名。Laravel API - Vue.js返回帖子用户

当使用我用这样的事情在foreach循环返回作者姓名刀片模板引擎:

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

当我回到岗位低谷的API,我得到没有得到任何用户信息,用户标识除外。我如何获得属于这篇文章的用户信息?

{ 
    "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); 
    } 

回答

3

您可以使用预先加载为:

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

Brainfart ...感谢您的回答,我应该想到这一点...... –