✨ 博客开发:分类标签与搜索功能开发
XiaoYu
这次新增 分类(Category)与标签(Tag) 和 多维度搜索 功能,支持每篇文章可关联多个分类和标签,并在文章编辑页完成关联与修改。这篇文章简要记录开发过程和关键实现。
功能目标
-
每篇文章支持关联多个分类、多个标签(多对多)
-
支持新建、编辑文章时选择分类和标签
-
后台管理页面支持分类、标签的 CRUD 操作
-
支持按关键词、分类和标签等条件搜索
文章分类标签开发
数据模型设计(Prisma)
在 schema.prisma 中定义多对多关系表结构:
js
model Post {
id Int @id @default(autoincrement())
title String
content String
...
PostCategory PostCategory[]
PostTag PostTag[]
}
model Category {
id Int @id @default(autoincrement())
name String @unique
posts PostCategory[]
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts PostTag[]
}
model PostCategory {
id Int @id @default(autoincrement())
post Post @relation(fields: [postId], references: [id])
postId Int
category Category @relation(fields: [categoryId], references: [id])
categoryId Int
}
model PostTag {
id Int @id @default(autoincrement())
postId Int
tagId Int
...
}
编辑器前端实现
在文章编辑页中引入分类、标签多选功能:
js
<div className="mb-6">
<label>分类</label>
{allCategories.map(cat => (
<label key={cat.id}>
<input
type="checkbox"
checked={selectedCategoryIds.includes(cat.id)}
onChange={() => toggleCategory(cat.id)}
/>
{cat.name}
</label>
))}
</div>
<div className="mb-6">
<label>标签</label>
{allTags.map(tag => (
<label key={tag.id}>
<input
type="checkbox"
checked={selectedTagIds.includes(tag.id)}
onChange={() => toggleTag(tag.id)}
/>
{tag.name}
</label>
))}
</div>
后端接口更新
获取文章详情(附带分类/标签 ID)
js
const post = await prisma.post.findUnique({
where: { id },
include: {
PostCategory: { select: { categoryId: true } },
PostTag: { select: { tagId: true } },
}
})
更新文章并关联分类/标签
js
await prisma.post.update({
where: { id },
data: {
title, content, ...,
PostCategory: {
deleteMany: {},
create: categoryIds.map(id => ({ categoryId: id }))
},
PostTag: {
deleteMany: {},
create: tagIds.map(id => ({ tagId: id }))
}
}
})
文章搜索开发
-
🔑 关键词模糊匹配:支持文章标题、内容、标签、分类多字段搜索
-
📄 结果分页:支持 /search?q=关键词&page=2 多页跳转
-
💡 弹窗搜索框:仿 shadcn/ui 的命令面板风格,支持快捷键 Ctrl+K 调出
-
🎯 响应式 + 深色模式适配
-
👉 支持SEO
sequenceDiagram
participant U as 用户
participant FE as 前端(Next.js)
participant API as 接口(/api/search)
participant DB as 数据库(Prisma)
U->>FE: 输入关键词并点击搜索
FE->>API: 发起搜索请求(POST /api/search?query=关键词)
API->>DB: 使用 Prisma 查询文章标题、摘要、标签等
DB-->>API: 返回匹配结果列表
API-->>FE: 返回 JSON 格式的搜索结果
FE->>U: 渲染搜索结果页面(文章列表、分页等)
Note over FE, API: 可选逻辑:关键词为空时不发请求 / 显示提示
功能支持
✅ 支持编辑文章时选择分类 标签
✅ 分类管理
✅ 标签管理
✅ 搜索功能
Prisma 简化了关联数据的操作。具体查询效率、关联校验和权限控制,仍需要结合业务实现。
补充说明:代码为关系与交互示意,省略号不是可直接执行的语法。写入时需要校验权限、去重关联 ID,并区分“没有传分类/标签字段”和“传空数组主动清空”;搜索也必须限制文章可见范围。
评论
发表评论