['staff_userid', 'external_userid', 'roomid', 'session_type'], ]; } private function baseQuery() { $query = QywxMsgSession::where($this->searchWhere); $adminId = (int) ($this->params['admin_id'] ?? 0); if ($adminId > 0) { $wxId = Admin::where('id', $adminId)->value('work_wechat_userid'); if ($wxId) { $query->where('staff_userid', $wxId); } else { // 找不到对应企微 userid 时不返回任何会话 $query->where('id', 0); } } $keyword = trim((string) ($this->params['keyword'] ?? '')); if ($keyword !== '') { $kw = addcslashes($keyword, '%_\\'); $extIds = QywxExternalContact::whereLike('name', '%' . $kw . '%')->column('external_userid'); $query->where(function ($q) use ($kw, $extIds) { $q->whereLike('last_msg_summary', '%' . $kw . '%'); if ($extIds) { $q->whereOr('external_userid', 'in', $extIds); } }); } if (!empty($this->params['only_unread'])) { $query->where('unread_staff', '>', 0); } return $query->order('last_msg_time', 'desc'); } public function lists(): array { $rows = $this->baseQuery() ->limit($this->limitOffset, $this->limitLength) ->select() ->toArray(); if (empty($rows)) { return []; } $extIds = array_values(array_unique(array_filter(array_map( fn ($r) => (string) ($r['external_userid'] ?? ''), $rows )))); $extMap = []; if ($extIds) { $extMap = QywxExternalContact::whereIn('external_userid', $extIds) ->column('name,avatar,type,gender,corp_name,unionid', 'external_userid'); } $staffIds = array_values(array_unique(array_filter(array_map( fn ($r) => (string) ($r['staff_userid'] ?? ''), $rows )))); $staffMap = []; if ($staffIds) { $staffMap = Admin::whereIn('work_wechat_userid', $staffIds) ->column('id,name,avatar', 'work_wechat_userid'); } foreach ($rows as &$r) { $r['customer'] = $extMap[$r['external_userid']] ?? null; $r['staff'] = $staffMap[$r['staff_userid']] ?? null; } unset($r); return $rows; } public function count(): int { return $this->baseQuery()->count(); } }