You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

一对一聊天开发:如何新增「其他用户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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:56:07