Laravel/Inertia项目中如何通过评论表外键获取关联用户的用户名
解决方案
步骤1:为Comment模型添加用户关联
打开app/Models/Comment.php文件,添加用户关联方法,建立评论和发布者的一对一关联:
// 需先引入User模型 use App\Models\User; public function user() { return $this->belongsTo(User::class); }
同时可以顺便优化Blog模型的作者关联,后续查询更方便:
// app/Models/Blog.php 中添加 use App\Models\User; public function user() { return $this->belongsTo(User::class); }
步骤2:修改控制器查询逻辑,预加载评论关联的用户数据
修改BlogController的show方法,查询评论时通过with('user')预加载关联的用户数据,避免出现N+1查询问题:
public function show(Blog $blog) { return Inertia::render('Components/Blog', [ 'blog' => [ 'id' => $blog->id, 'name' => $blog->user->name, 'title' => $blog->title, 'body' => $blog->body, 'created_at' => $blog->created_at, 'updated_at' => $blog->updated_at, // 预加载每条评论对应的发布者数据 'comments' => $blog->blogComments()->orderByDate()->with('user')->get()->all(), ], ]); }
这里把方法参数从$id改为$blog更符合语义,因为隐式模型绑定注入的是Blog实例,原命名容易产生误解。
步骤3:修改Vue组件渲染评论用户名
直接在遍历评论时通过comment.user.name获取发布者名称即可,如需兼容已删除用户的场景,可以加可选链和默认值避免报错:
<template> <div> <div v-for="comment in blog.comments" :key="comment.id" class="hover:bg-gray-100 focus-within:bg-gray-100" > <p>评论发布者:{{ comment.user?.name ?? '已注销用户' }}</p> <p>comment id: {{ comment.id }}</p> <p>comment body: {{ comment.body }}</p> </div> </div> </template> <script> export default { props: { blog: Object, }, }; </script>
内容的提问来源于stack exchange,提问作者Beaumont
相关产品推荐
相关产品推荐

