gpt4 book ai didi

Laravel API - Vue.js 返回用户的帖子

转载 作者:搜寻专家 更新时间:2023-10-30 23:00:35 24 4
gpt4 key购买 nike

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

当使用 blade 模板引擎时,我在 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);
}

最佳答案

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

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

关于Laravel API - Vue.js 返回用户的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com