Skip to content

Commit

Permalink
DEV: Category#with_ancestor_ids
Browse files Browse the repository at this point in the history
  • Loading branch information
danielwaterworth committed May 10, 2024
1 parent 2a2eaf8 commit 1b4e1d2
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions app/models/category.rb
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,37 @@ def self.preload_user_fields!(guardian, categories)
end
end

def self.with_ancestor_ids
categories =
select(
"categories.id",
"ARRAY[]::integer[] AS ancestor_ids",
"categories.parent_category_id AS ancestor_id",
)

(SiteSetting.max_category_nesting - 2).times do
categories =
Category.from("(#{categories.to_sql}) AS category_ancestors").select(
"category_ancestors.id",
"category_ancestors.ancestor_id || category_ancestors.ancestor_ids AS ancestor_ids",
"(SELECT c.parent_category_id FROM categories c WHERE c.id = category_ancestors.ancestor_id) AS ancestor_id",
)
end

categories =
Category.from("(#{categories.to_sql}) AS category_ancestors").select(
"category_ancestors.id",
"(SELECT array_remove(category_ancestors.ancestor_id || category_ancestors.ancestor_ids, NULL)) AS ancestor_ids",
)

categories =
Category.joins(
"INNER JOIN (#{categories.to_sql}) AS category_ancestors ON categories.id = category_ancestors.id",
).select("categories.*", "category_ancestors.ancestor_ids")

Category.from("(#{categories.to_sql}) AS categories")
end

def self.ancestors_of(category_ids)
ancestor_ids = []

Expand Down

0 comments on commit 1b4e1d2

Please sign in to comment.