Files
cunkebao_v3/Server/application/chukebao/controller/WechatChatroomController.php
2025-09-17 16:51:11 +08:00

81 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\chukebao\controller;
use library\ResponseHelper;
use think\Db;
class WechatChatroomController extends BaseController
{
public function getList(){
$page = $this->request->param('page', 1);
$limit = $this->request->param('limit', 10);
$accountId = $this->getUserInfo('s2_accountId');
if (empty($accountId)){
return ResponseHelper::error('请先登录');
}
$query = Db::table('s2_wechat_chatroom')
->where(['accountId' => $accountId,'isDeleted' => 0])
->order('id desc');
$list = $query->page($page, $limit)->select();
$total = $query->count();
// 提取所有聊天室ID用于批量查询
$chatroomIds = array_column($list, 'id');
// 一次性查询所有聊天室的未读消息数量
$unreadCounts = [];
if (!empty($chatroomIds)) {
$unreadResults = Db::table('s2_wechat_message')
->field('wechatChatroomId, COUNT(*) as count')
->where('wechatChatroomId', 'in', $chatroomIds)
->where('isRead', 0)
->group('wechatChatroomId')
->select();
foreach ($unreadResults as $result) {
$unreadCounts[$result['wechatChatroomId']] = $result['count'];
}
}
// 一次性查询所有聊天室的最新消息
$latestMessages = [];
if (!empty($chatroomIds)) {
// 使用子查询获取每个聊天室的最新消息ID
$subQuery = Db::table('s2_wechat_message')
->field('MAX(id) as max_id, wechatChatroomId')
->where('wechatChatroomId', 'in', $chatroomIds)
->group('wechatChatroomId')
->buildSql();
// 查询最新消息的详细信息
$messageResults = Db::table('s2_wechat_message')
->alias('m')
->join([$subQuery => 'sub'], 'm.id = sub.max_id')
->field('m.*, sub.wechatChatroomId')
->select();
foreach ($messageResults as $message) {
$latestMessages[$message['wechatChatroomId']] = $message;
}
}
// 处理每个聊天室的数据
foreach ($list as $k => &$v) {
$v['createTime'] = !empty($v['createTime']) ? date('Y-m-d H:i:s', $v['createTime']) : '';
$v['updateTime'] = !empty($v['updateTime']) ? date('Y-m-d H:i:s', $v['updateTime']) : '';
$config = [
'unreadCount' => isset($unreadCounts[$v['id']]) ? $unreadCounts[$v['id']] : 0,
'chat' => isset($latestMessages[$v['id']]),
'msgTime' => isset($latestMessages[$v['id']]) ? $latestMessages[$v['id']]['wechatTime'] : 0
];
$v['config'] = $config;
}
unset($v);
return ResponseHelper::success(['list'=>$list,'total'=>$total]);
}
}