【发布时间】:2019-02-05 15:44:11
【问题描述】:
我目前正在学习 Vue 并使用 laravel 作为我的后端。我为论坛设置了一个关系,它将从下面的 User 模型示例中获取作者的用户名:
public function fetchAuthor()
{
return $this->belongsTo('App\User', 'author', 'id');
}
如果我从主页进入论坛,则会正确显示用户名(而不是主题的存储用户 ID),
在提交新主题时,它会抛出以下错误:
[Vue 警告]:渲染错误:“TypeError:无法读取属性 未定义的“用户名”
我环顾四周,似乎找不到哪个有效的答案。这是我的 Vue 脚本代码:
<script>
export default {
data(){
return {
topics: {
author: '',
topic: '',
content: '',
},
errors: [],
forumTopics: [],
}
},
mounted()
{
this.fetchTopics();
},
ready() {
this.updateContent()
},
methods: {
updateContent: function (){
this.$http.get('api/gameForum')
.then(response => {
this.forumTopics = response.data.forumTopics
});
setTimeout(this.updateContent, 1000);
},
initAddTopic()
{
$("#add_topic_modal").modal("show");
},
createTopic()
{
axios.post('api/gameForum', {
topic: this.topics.topic,
content: this.topics.content,
})
.then(response => {
this.reset();
$("#add_topic_modal").modal("hide");
this.forumTopics.push(response.data.topics);
})
.catch(error => {
this.errors = [];
if (error.response.data.errors.topic) {
this.errors.push(error.response.data.errors.topic[0]);
}
if (error.response.data.errors.content) {
this.errors.push(error.response.data.errors.content[0]);
}
});
},
reset()
{
this.topics.topic = '';
this.topics.content = ''
},
fetchTopics()
{
axios.get('api/gameForum')
.then(response => {
this.forumTopics = response.data.forumTopics;
});
},
}
}
</script>
这里是控制器(我将展示我正在使用的索引函数和存储函数:
public function index()
{
if (Auth::user()->usergroup > 2)
{
$fetchTopics = ForumTopics::where('forum_type', 'game forum')
->orderBy('updated_at', 'desc')
->with('fetchAuthor')
->get();
} else {
$fetchTopics = ForumTopics::where('forum_type', 'game forum')
->where('deleted', 0)
->orderBy('updated_at', 'desc')
->with('fetchAuthor')
->get();
}
return response()->json([
'forumTopics' => $fetchTopics
],200);
}
这里是存储功能
public function store(Request $request)
{
$this->validate($request, [
'topic' => 'required|max:40',
'content' => 'required'
]);
$forumTopics = ForumTopics::create([
'author' => Auth::user()->id,
'topic' => $request->get('topic'),
'content' => $request->get('content'),
'forum_type' => 'Game Forum'
]);
return response()->json([
'topics' => $forumTopics,
'message' => 'Success'
], 200);
}
这是调用用户名的表格视图显示:
<table class="table table-responsive" style="margin-top:1%;">
<tbody>
<tr v-for="topic in forumTopics">
<td>
{{ topic.fetch_author.username }}
</td>
<td>
{{ topic.topic }}
</td>
</tr>
</tbody>
</table>
注意 - 你可以看到我已经尝试运行 updateContent() 函数,这是我来这里之前的最后一次尝试。
【问题讨论】:
-
您能否在代码中包含您引用用户名的部分?我在提供的任何代码 sn-ps 中都没有看到用户名
-
@AlexHarris,很抱歉我现在添加了它。
-
显然
forumTopics的至少一个成员被重置为没有fetch_author成员的值。 -
@RoyJ,对我能做什么有什么建议吗?我也试过删除 reset() 但它仍然做同样的事情