一对一聊天开发:如何新增「其他用户ID」列并筛选目标ID
解决方案
你可以通过在查询中添加计算字段的方式,用SQL的CASE语句判断当前用户所在的列,从而提取出聊天对象的ID,具体修改后的代码如下:
$currentUserId = Auth::id(); $rooms = Chat::select( '*', DB::raw("CASE WHEN user_1 = ? THEN user_2 ELSE user_1 END AS other_user"), [$currentUserId] ) ->where('user_1', $currentUserId) ->orWhere('user_2', $currentUserId) ->latest() ->get(); return view('users.chats', [ 'room_id' => $rooms, 'selectedUser' => false ]);
代码说明
- 先把当前用户ID存入变量
$currentUserId,避免重复调用Auth::id(); - 使用
DB::raw结合CASE语句:如果user_1是当前用户,other_user就取user_2的值,否则取user_1的值,以此得到聊天对象的ID; - 用参数绑定(
?和[$currentUserId])的方式避免SQL注入风险; - 查询结果里的每个
Chat实例都会新增other_user属性,直接调用$room->other_user就能获取聊天对象的ID。
如果后续需要获取聊天对象的更多信息(比如昵称、头像),可以在Chat模型中添加关联:
// 在Chat模型中定义关联 public function otherUser() { return $this->belongsTo(User::class, 'other_user'); }
然后在查询时加入关联预加载,提升性能:
$rooms = Chat::select( '*', DB::raw("CASE WHEN user_1 = ? THEN user_2 ELSE user_1 END AS other_user"), [$currentUserId] ) ->where('user_1', $currentUserId) ->orWhere('user_2', $currentUserId) ->with('otherUser:id,name,avatar') // 只加载需要的字段 ->latest() ->get();
之后就能通过$room->otherUser->name直接获取对方的昵称了。
内容的提问来源于stack exchange,提问作者Aziz
相关产品推荐
相关产品推荐

