如何在Laravel中查询所有帖子并添加登录用户是否已点赞的标记字段
解决方案
方法1:直接修改你当前的查询构造器代码
你需要在关联post_likes表的时候额外增加「点赞用户为当前登录用户」的过滤条件,再通过条件判断生成标记位,修改后代码如下:
// 先获取当前登录用户ID,游客状态默认设为0即可 $currentUserId = auth()->id() ?? 0; $postData = DB::table('posts') ->leftJoin('users', 'users.id', '=', 'posts.user_id') ->leftJoin('user_profile', 'user_profile.id', '=', 'posts.user_id') // 关联点赞表时只关联当前登录用户的点赞记录 ->leftJoin('post_likes', function ($join) use ($currentUserId) { $join->on('posts.id', '=', 'post_likes.post_id') ->where('post_likes.user_id', '=', $currentUserId); }) ->select( 'posts.id as postId', 'users.*', 'posts.post_caption', 'posts.post_media', 'posts.created_at', 'user_profile.profile_pic', // 新增标记位:如果存在当前用户的点赞记录则为1,否则为0 DB::raw('IF(post_likes.id IS NOT NULL, 1, 0) as postIsLiked') ) ->get() ->toArray();
查询结果里每条记录都会带postIsLiked字段,前端直接判断这个字段的值切换点赞图标样式即可。
方法2:Eloquent 模型更优雅的实现(推荐)
如果你用了Eloquent模型,不需要手写关联查询,直接用withCount即可实现,性能更好也更易维护:
- 先在
Post模型中定义点赞关联:
public function postLikes() { return $this->hasMany(PostLike::class); }
- 查帖子的时候直接加统计条件:
$currentUserId = auth()->id() ?? 0; $postData = Post::with(['user', 'userProfile']) ->withCount(['postLikes as postIsLiked' => function ($query) use ($currentUserId) { $query->where('user_id', $currentUserId); }]) ->get() ->toArray();
生成的postIsLiked字段值就是0或1,和上面查询构造器效果完全一致。
注意事项
如果是未登录的游客状态,$currentUserId为0,所有帖子的postIsLiked都会默认返回0,符合未登录不能点赞的业务逻辑。
内容的提问来源于stack exchange,提问作者Santosh Dangare
相关产品推荐
相关产品推荐

