后台基本功能完成,待完善:普通用户前端页面
This commit is contained in:
@@ -4,7 +4,7 @@ import { QuestionCategoryModel } from '../models/questionCategory';
|
||||
export class QuestionCategoryController {
|
||||
static async getCategories(req: Request, res: Response) {
|
||||
try {
|
||||
const categories = await QuestionCategoryModel.findAll();
|
||||
const categories = await QuestionCategoryModel.findAllWithQuestionCounts();
|
||||
res.json({
|
||||
success: true,
|
||||
data: categories
|
||||
|
||||
@@ -7,6 +7,10 @@ export interface QuestionCategory {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface QuestionCategoryWithQuestionCount extends QuestionCategory {
|
||||
questionCount: number;
|
||||
}
|
||||
|
||||
export class QuestionCategoryModel {
|
||||
// 获取所有题目类别,包括从题目表中聚合的新类别
|
||||
static async findAll(): Promise<QuestionCategory[]> {
|
||||
@@ -125,4 +129,32 @@ export class QuestionCategoryModel {
|
||||
await run(`UPDATE questions SET category = '通用' WHERE category = ?`, [existing.name]);
|
||||
await run(`DELETE FROM question_categories WHERE id = ?`, [id]);
|
||||
}
|
||||
|
||||
static async findAllWithQuestionCounts(): Promise<QuestionCategoryWithQuestionCount[]> {
|
||||
const categories = await this.findAll();
|
||||
|
||||
try {
|
||||
const countSql = `
|
||||
SELECT
|
||||
COALESCE(NULLIF(TRIM(category), ''), '通用') as name,
|
||||
COUNT(*) as questionCount
|
||||
FROM questions
|
||||
GROUP BY COALESCE(NULLIF(TRIM(category), ''), '通用')
|
||||
`;
|
||||
const rows: Array<{ name: string; questionCount: number }> = await query(countSql);
|
||||
const countByName = new Map<string, number>(
|
||||
rows.map((r) => [String(r.name), Number(r.questionCount ?? 0)]),
|
||||
);
|
||||
|
||||
return categories.map((c) => ({
|
||||
...c,
|
||||
questionCount: countByName.get(c.name) ?? 0,
|
||||
}));
|
||||
} catch {
|
||||
return categories.map((c) => ({
|
||||
...c,
|
||||
questionCount: 0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user