Problem consult self-referenced table

5

I want to be able to put together my dynamic menu with the following data structure:

The menu is restricted by user roles. To my table menu, I have added a column id_menu_padre to be able to build the structure type "tree" that my menu should have.

The problem I have is that I can not find a way to do my query to show me the results I get, including the green one:

      $roles_menu =  collect(DB::select("
                                    select m.id_menu as menu_id,
                                    m.des_menu as menu_des,
                                    m.url_menu as url, 
                                    m.id_menu_padre as id_menu_padre, 
                                    (select des_menu from menu where menu.id_menu = m.id_menu_padre) as des_menu_padre 

                                   from menu m
                                   left join menu me on m.id_menu = me.id_menu_padre  
                                       join rol_menu on rol_menu.id_menu = m.id_menu 
                                       join roles on rol_menu.id_rol = roles.id_role AND 
                                           roles.id_role = $id_rol"))->toArray();

    return $roles_menu;

(I update)

The only way I have found to get the results I need is the following:

WITH MenuCTE AS
( 
SELECT H.id_menu AS id_menu, H.des_menu AS des_menu, H.url_menu AS url_menu, 
id_menu_padre 
FROM menu H, rol_menu RM, roles R
WHERE RM.id_menu = H.id_menu AND RM.id_rol = R.id_role AND R.id_role = 23 
UNION ALL
SELECT P.id_menu, P.des_menu, P.url_menu, P.id_menu_padre 
FROM menu P, rol_menu RM, roles R
INNER JOIN MenuCTE s ON id_menu = s.id_menu_padre 
UNION ALL
SELECT P.id_menu, P.des_menu, P.url_menu, P.id_menu_padre 
FROM menu P 
 JOIN MenuCTE s ON P.id_menu = s.id_menu_padre 
) 
 SELECT DISTINCT * FROM MenuCTE  

However, the fact of having to use "distinct" indicates to me that surely there is something I am doing wrong.

SELECT DISTINCT * FROM MenuCTE  
    
asked by Virginia 03.09.2018 в 18:13
source

1 answer

0

For now, keep in mind that with

UNION ALL

You are asking him to show you the common lines including duplicates. Try changing the clause by

UNION

and you should not get duplicates. In any case, I understand that the tables where you keep the menu entries will contain a few tens, at most hundreds of records. It's not worth optimizing those queries, you have to focus on tables that contain many more records.

    
answered by 26.12.2018 в 10:48