This commit is contained in:
2025-09-01 21:02:19 +08:00
parent ebacec8e16
commit 16a8cd5506

View File

@@ -204,7 +204,14 @@ func (r *GormArticleRepository) Search(ctx context.Context, query *repoQueries.S
}
if query.CategoryID != "" {
dbQuery = dbQuery.Where("category_id = ?", query.CategoryID)
// 如果指定了分类ID只查询该分类的文章包括没有分类的文章CategoryID为空字符串时)
if query.CategoryID == "null" || query.CategoryID == "" {
// 查询没有分类的文章
dbQuery = dbQuery.Where("category_id IS NULL OR category_id = ''")
} else {
// 查询指定分类的文章
dbQuery = dbQuery.Where("category_id = ?", query.CategoryID)
}
}
if query.AuthorID != "" {
@@ -270,13 +277,23 @@ func (r *GormArticleRepository) ListArticles(ctx context.Context, query *repoQue
}
if query.CategoryID != "" {
dbQuery = dbQuery.Where("category_id = ?", query.CategoryID)
// 如果指定了分类ID只查询该分类的文章包括没有分类的文章CategoryID为空字符串时)
if query.CategoryID == "null" || query.CategoryID == "" {
// 查询没有分类的文章
dbQuery = dbQuery.Where("category_id IS NULL OR category_id = ''")
} else {
// 查询指定分类的文章
dbQuery = dbQuery.Where("category_id = ?", query.CategoryID)
}
}
if query.TagID != "" {
// 通过标签关联表筛选
dbQuery = dbQuery.Joins("JOIN article_tag_relations ON articles.id = article_tag_relations.article_id").
Where("article_tag_relations.tag_id = ?", query.TagID)
// 如果指定了标签ID只查询有关联该标签的文章
// 使用子查询而不是JOIN避免影响其他查询条件
subQuery := r.db.WithContext(ctx).Table("article_tag_relations").
Select("article_id").
Where("tag_id = ?", query.TagID)
dbQuery = dbQuery.Where("id IN (?)", subQuery)
}
if query.Title != "" {