Laravel如何获取每条评论对应的用户信息?
如何在Laravel中让评论关联用户,实现视图直接调用
$comment->user? 问题背景
我现在有这些Laravel模型代码:
class Post extends Model { protected $primaryKey = 'post_id'; public function comments() { return $this->hasMany(Comment::class, 'post_id', 'post_id'); } } class Comment extends Model { protected $primaryKey = 'comment_id'; public function post() { return $this->belongsTo(Post::class, 'post_id'); } } class User extends Authenticatable { protected $primaryKey = 'user_id'; public function comments() { return $this->hasMany(Comment::class, 'user_id', 'commenter_id'); } } class MyController extends Controller { public function post($id = null) { $post = Post::where('post_id', $id)->first(); $comments = $post->comments; } }
想要在视图里通过下面的方式直接获取评论对应的用户信息:
@foreach($post->comments as $comment) {{ $comment->user->first_name.' '.$comment->user->last_name }} @endforeach
原本猜测需要用hasManyThrough,但觉得这个关联太复杂,有点困惑。
解决方案:给Comment模型添加belongsTo关联
其实你完全不需要hasManyThrough,这个场景下每个评论属于一个用户,直接在Comment模型里添加和User的belongsTo关联就足够了,步骤如下:
- 修改Comment模型,添加user关联
在Comment类里新增一个user()方法,指定关联的外键(你的评论表中关联用户的字段是commenter_id,对应用户表的主键user_id):
class Comment extends Model { protected $primaryKey = 'comment_id'; public function post() { return $this->belongsTo(Post::class, 'post_id'); } // 新增:关联评论所属的用户 public function user() { // 参数说明:关联模型、评论表的外键、用户表的主键 return $this->belongsTo(User::class, 'commenter_id', 'user_id'); } }
- 控制器中预加载关联,避免N+1查询问题
为了避免每条评论都单独查询一次用户的N+1查询问题,在获取Post的时候,用with('comments.user')预加载评论和对应的用户数据:
class MyController extends Controller { public function post($id = null) { // 预加载comments及其关联的user $post = Post::with('comments.user')->where('post_id', $id)->first(); // 把post传递到视图 return view('你的视图名称', compact('post')); } }
为什么不用hasManyThrough?
hasManyThrough是用来处理间接关联的场景(比如通过Post获取所有评论的用户集合),但你现在需要的是每个评论直接关联到它的发布者,belongsTo是最直接且简单的方案,完全能满足你的需求。
现在你就可以在视图里像你想要的那样,直接通过$comment->user调用用户信息啦!
内容的提问来源于stack exchange,提问作者kodfire
相关产品推荐
相关产品推荐

