V
V
Vladimir2019-10-29 05:12:02
MySQL
Vladimir, 2019-10-29 05:12:02

How to display the menu from the database?

Good morning. Please help. I've been warming my head for several hours, I don't understand how to display the menu.
I have such a script at the moment, it finds all matching sub-items and displays them in arrays. Later I need to display text under these id
parent_id - id of sub -items
id - id of items
title - text of items

connection.query("SELECT * FROM menu", function(err,res){
    const menu = res.map(list => list)

    for(i=0; i<menu.length; i++) {
      connection.query("SELECT * FROM menu WHERE parent_id = '"+menu[i].id+"'", function(err,res){
        
      })
    }

  })

5db79feb003d0277675376.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2019-10-29
@HistoryART

connection.query('SELECT * FROM menu', (err, result) => {
  if(err) {
    console.error(err);
    return;
  }
  const index = result.reduce((acc, row) => ({...acc, [row.id]: row}), {});
  const menu = [];
  for(const row of result) {
    if(row.parent_id === 0) {
      menu.push(row);
      continue;
    }
    const parent = index[row.parent_id];
    if(!parent) {
      console.warn(`Undefined parent with id ${row.parent_id}`);
      continue;
    }
    if(!parent.children) {
      parent.children = [];
    }
    parent.children.push(row);
  }
  console.log(menu);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question