diff --git a/internal/infrastructure/database/repositories/article/gorm_article_repository.go b/internal/infrastructure/database/repositories/article/gorm_article_repository.go index 8b2ad80..fc5ab52 100644 --- a/internal/infrastructure/database/repositories/article/gorm_article_repository.go +++ b/internal/infrastructure/database/repositories/article/gorm_article_repository.go @@ -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 != "" {