50 ? 50 : (int)$pageSize; $page = $page <= 0 ? 1 : (int)$page; $where = [ ['post_id', '=', $postId], ['status', '=', 1] ]; $total = $this->where($where)->count(); $list = []; if ($total > 0) { $list = $this->alias('c') ->field('c.*, u.nickname as author_name, u.avatar as author_avatar') ->leftJoin('user u', 'u.uid = c.uid') ->where($where) ->order('c.create_time', 'asc') ->page($page, $pageSize) ->select(); if (!empty($list)) { $list = $list->toArray(); foreach ($list as &$item) { if (!empty($item['create_time'])) { $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']); } } } } return [ 'list' => $list, 'total' => $total, 'page' => $page, 'pageSize' => $pageSize ]; } /** * 添加评论 * @param int $uid 用户ID * @param int $postId 帖子ID * @param string $content 评论内容 * @return array [success, message, data] */ public function addComment($uid, $postId, $content) { try { self::beginTrans(); // 检查帖子是否存在且状态正常 $post = Db::name('forum_post')->where('id', $postId)->where('status', 1)->find(); if (!$post) { self::rollbackTrans(); return [0, '帖子不存在或已被禁用']; } $insertData = [ 'post_id' => $postId, 'uid' => $uid, 'content' => trim($content), 'status' => 1, 'create_time' => time(), 'update_time' => time(), ]; $result = $this->insert($insertData); if (!$result) { self::rollbackTrans(); return [0, '评论失败']; } // 更新帖子评论数 Db::name('forum_post')->where('id', $postId)->inc('comment_count')->update(); self::commitTrans(); return [1, '评论成功', ['post_id' => $postId]]; } catch (\Exception $e) { self::rollbackTrans(); return [0, '评论失败:' . $e->getMessage()]; } } /** * 删除评论 * @param int $id 评论ID * @param int $uid 用户ID * @return array [success, message] */ public function deleteComment($id, $uid) { try { self::beginTrans(); $comment = $this->where('id', $id)->where('uid', $uid)->find(); if (!$comment) { self::rollbackTrans(); return [0, '评论不存在或无权删除']; } // 删除评论 $this->where('id', $id)->delete(); // 更新帖子评论数 Db::name('forum_post')->where('id', $comment['post_id'])->dec('comment_count')->update(); self::commitTrans(); return [1, '删除成功']; } catch (\Exception $e) { self::rollbackTrans(); return [0, '删除失败:' . $e->getMessage()]; } } /** * 获取用户评论列表 * @param int $uid 用户ID * @param int $page 页码 * @param int $pageSize 每页数量 * @return array */ public function getUserComments($uid, $page = 1, $pageSize = 20) { $pageSize = $pageSize > 50 ? 50 : (int)$pageSize; $page = $page <= 0 ? 1 : (int)$page; $total = $this->where('uid', $uid)->count(); $list = []; if ($total > 0) { $list = $this->alias('c') ->field('c.*, p.title as post_title, p.id as post_id') ->leftJoin('forum_post p', 'p.id = c.post_id') ->where('c.uid', $uid) ->order('c.create_time', 'desc') ->page($page, $pageSize) ->select(); if (!empty($list)) { $list = $list->toArray(); foreach ($list as &$item) { if (!empty($item['create_time'])) { $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']); } } } } return [ 'list' => $list, 'total' => $total, 'page' => $page, 'pageSize' => $pageSize ]; } }