38 lines
1.3 KiB
PHP
38 lines
1.3 KiB
PHP
|
<?php
|
||
|
// TODO: 点赞数
|
||
|
$sql = "SELECT lw.id, u.username AS author, lw.content, COUNT(c.id) AS likes
|
||
|
FROM love_wall lw
|
||
|
LEFT JOIN users u ON lw.user_id = u.id
|
||
|
LEFT JOIN comments c ON lw.id = c.love_wall_id
|
||
|
GROUP BY lw.id, u.username, lw.content
|
||
|
ORDER BY lw.created_at DESC";
|
||
|
|
||
|
$stmt = $pdo->query($sql);
|
||
|
$posts = $stmt->fetchAll();
|
||
|
|
||
|
// 为每个post添加评论
|
||
|
foreach ($posts as &$post) {
|
||
|
$commentSql = "SELECT c.id, u.username AS author, c.content
|
||
|
FROM comments c
|
||
|
JOIN users u ON c.user_id = u.id
|
||
|
WHERE c.love_wall_id = :love_wall_id";
|
||
|
$commentStmt = $pdo->prepare($commentSql);
|
||
|
$commentStmt->execute([':love_wall_id' => $post['id']]);
|
||
|
$post['comments'] = $commentStmt->fetchAll(PDO::FETCH_ASSOC); // 确保是关联数组
|
||
|
// TODO: 头像
|
||
|
$post['avatar'] = '/placeholder.svg?height=40&width=40';
|
||
|
|
||
|
// 清理不需要的索引
|
||
|
$post = [
|
||
|
'id' => $post['id'],
|
||
|
'author' => $post['author'],
|
||
|
'avatar' => $post['avatar'],
|
||
|
'content' => $post['content'],
|
||
|
'likes' => (int)$post['likes'], // 转换为整数
|
||
|
'comments' => $post['comments']
|
||
|
];
|
||
|
}
|
||
|
|
||
|
echo json_encode($posts, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||
|
?>
|