Ordinamento delle categorie usando SQL

The following code changes the order of categories to be alphanumeric using SQL.

Preconditions.
Postgres backend

UPDATE categories
SET POSITION = subquery.position
FROM (
	SELECT POSITION
	, CASE WHEN category_id = 0 THEN parent_category_id ELSE category_id END category_id 
	, CASE WHEN category_id = 0 THEN parent_category_name ELSE category_name END category_name 
	FROM (
		SELECT ROW_NUMBER - 1 AS POSITION
		, parent_category_id
		, parent_category_name
		, category_id
		, category_name
		FROM ( SELECT row_number() OVER ( ORDER BY parent_category_name, category_name )
		, * FROM (
		SELECT * FROM (
			SELECT id parent_category_id
			, name parent_category_name 
			, 0 category_id
			, cast('' AS text) category_name
			FROM categories 
			WHERE parent_category_id IS NULL ORDER BY name
		) parent_categories
		UNION 
		(
			SELECT child.parent_category_id
			, parent.name parent_category_name 
			, child.id category_id
			, child.name category_name
			FROM categories child
			INNER JOIN categories parent
			ON child.parent_category_id = parent.id
			WHERE child.parent_category_id IS NOT NULL ORDER BY child.name
		) 
		) parents_with_children
		ORDER BY parent_category_name, category_name
		) ordered_parents_with_children
		ORDER BY ROW_NUMBER
	) category_positions_sorted_alphabetically
) subquery
WHERE id = subquery.category_id ;

I ran the code by starting up a psql session.

/var/discourse/launcher enter app
su postgres
psql discourse

and then executing the SQL.

Running from rails console.

ActiveRecord::Base.connection.execute("UPDATE categories SET POSITION = subquery.position FROM ( SELECT POSITION , CASE WHEN category_id = 0 THEN parent_category_id ELSE category_id END category_id , CASE WHEN category_id = 0 THEN parent_category_name ELSE category_name END category_name FROM ( SELECT ROW_NUMBER - 1 AS POSITION , parent_category_id , parent_category_name , category_id , category_name FROM ( SELECT row_number() OVER ( ORDER BY parent_category_name, category_name ) , * FROM ( SELECT * FROM ( SELECT id parent_category_id , name parent_category_name , 0 category_id , cast('' AS text) category_name FROM categories WHERE parent_category_id IS NULL ORDER BY name ) parent_categories UNION ( SELECT child.parent_category_id , parent.name parent_category_name , child.id category_id , child.name category_name FROM categories child INNER JOIN categories parent ON child.parent_category_id = parent.id WHERE child.parent_category_id IS NOT NULL ORDER BY child.name ) ) parents_with_children ORDER BY parent_category_name, category_name ) ordered_parents_with_children ORDER BY ROW_NUMBER ) category_positions_sorted_alphabetically ) subquery WHERE id = subquery.category_id")
2 Mi Piace

I’ve not tested this recently but here’s at least a hint for how to alpha-sort categories at the rails console:

# alpha sort all categories matching search and their sub-categories

  def sort_matching_categories_and_subcategories(search)
    categories = Category.where("name like ?", search)
    position = 100
    categories.order(:name).each do |cat|
      position += 5
      cat.position = position
      cat.save!()
      c_position = 0
      children = Category.where(:parent_category_id=>cat.id)
      children.order(:name).each do |c|
        c_position += 5
        c.position = c_position
        c.save!()
      end
    end
  end


 # alpha sort subcategories of a single category matching search
def sort_matching_subcategories(search)
  categories = Category.where("name like ?", search)
  if categories.count > 1
    puts "Found more than one category"
  end
  categories.order(:name).each do |cat|
    c_position = 5
    children = Category.where(:parent_category_id=>cat.id)
    children.order(:name).each do |c|
      c_position += 5
      c.position = c_position
      c.save!()
    end
  end
end
1 Mi Piace

Thanks @pfaffman

Based on your ruby code I came up with

def sort_categories_by_name(skip=0)
  
  parents = Category.where("parent_category_id is null")
  position = 0
  parents.order(:name).each do |parent|
    parent.position = position
    parent.save!()
    position += (1+skip)
    children = Category.where(:parent_category_id=>parent.id)
    children.order(:name).each do |child|
      child.position = position
      child.save!()
      position += (1+skip)  
    end
  end
  
  position += -(1+skip)  
  return position
  
end

sort_categories_by_name
1 Mi Piace

Ciao. È la prima volta che sono qui.
Questo post chiarisce che le categorie non possono essere impostate in ordine alfabetico tramite un’opzione GUI?

Grazie

In un certo senso. Ci sono impostazioni per ordinarle in modo fisso. Penso che tu debba prima impostare una configurazione di sistema (cerca ‘fisso’, forse) e poi puoi farlo nell’interfaccia utente.

Se ne hai una dozzina, non è troppo complicato farlo nell’interfaccia utente (quell’interfaccia ha dato problemi e non so come funzioni attualmente, quindi alcune di queste informazioni potrebbero essere errate); se ne hai centinaia e non cambiano, ho scritto una volta del codice da eseguire nella console per ordinarle. Se ne hai molte, le modifichi continuamente e vuoi mantenerle ordinate, avresti bisogno di un plugin.

Grazie. Sono solo un utente del forum Freephone e ho chiesto ai moderatori se potevano cambiare l’ordine elencato, ma la risposta iniziale è stata di consultare questo forum per capire come fare, quindi immagino che non sia un’opzione immediatamente disponibile.

Grazie ancora

A meno che non ci siano dozzine di categorie, non è proprio una cosa grave. E se ti hanno mandato qui invece di controllare nelle impostazioni da soli o chiedere qui da soli, significa semplicemente che non vogliono farlo.

Grazie ancora.

Penso che i moderatori non abbiano accesso al backend, che sembra essenziale.

Penso che scaricherò e ospiterò una copia, così dovrei riuscire a capire come fare ciò che voglio e condividere le informazioni :slight_smile: Deve esserci un amministratore in grado di gestire il problema.

1 Mi Piace

Sembra che uno dei moderatori sappia come farlo, ti farò sapere. Si dice che si possa fare tramite il menu hamburger??