【发布时间】:2022-01-07 20:54:50
【问题描述】:
我目前正在使用 Laravel、Inertiajs 和 Vuejs 创建博客,在获取用户名的逻辑方面需要一些帮助。
我有 3 张桌子:
用户:
- id (pk)
- 姓名
博客:
- id (pk)
- user_id(外键)
评论:
- id (pk)
- blog_id(外键)
- user_id(外键)
我有一个博客页面,它嵌套在来自 web.php 的动态路由中:
Route::get('/blogs/{id}', [BlogController::class, 'show'])->name("blogs.show");
博客页面包含博客文章和评论部分,由 BlogController 调用:
public function show(Blog $id)
{
$user = User::find($id->user_id)->name;
return Inertia::render('Components/Blog', [
'blog' => [
'id' => $id->id,
'name' => $user,
'title' => $id->title,
'body' => $id->body,
'created_at' => $id->created_at,
'updated_at' => $id->updated_at,
'comments' => $id->blogComments()->orderByDate()->get()->all(),
],
]);
}
就获取博主的用户名而言,它在$user = User::find($id->user_id)->name; 中工作得很好,并从Vue 组件作为blog 属性回调:<p>{{ blog.name }}</P>。现在,我想要的是在评论部分也调用用户名(见下面的目标)。
上面的注释部分是从 BlogController 中的 show() 方法调用的:
<template>
<div>
<div
v-for="comment in blog.comments"
:key="comment.id"
class="hover:bg-gray-100 focus-within:bg-gray-100"
>
<p>comment id: {{ comment.id }}</p>
<p>comment body: {{ comment.body }}</p>
</div>
</div>
</template>
<script>
export default {
props: {
blog: Object,
},
};
</script>
但我的问题是,我无法完全理解从 show() 方法中的 Users 表中获取用户名的逻辑。到目前为止,通过在控制器上调用 Comments 表中的外键到 Blogs 表中的主键,从 Blogs 表到 Comments 表存在一对多的关系:'comments' => $id->blogComments()->orderByDate()->get()->all(),
那么如何通过将 Comments 表(在 BlogController 中)中的外键调用到 Users 表中的主键来添加另一层?
我已经研究了几个小时,我确信我只是错过了一些简单的东西,所以如果有一双新的眼睛来看待这个,我将不胜感激。
谢谢。
【问题讨论】:
标签: laravel vue.js many-to-one inertiajs