Recursive tree-like table query with Slick

老子叫甜甜 提交于 2019-12-05 08:06:13

You could try calling SQL from slick. The SQL call to go up the hierarchy would look something like this (This is for SQL Server):

WITH org_name AS 
(
    SELECT DISTINCT
        parent.id AS parent_id,
        parentname.label as parent_label,
        child.id AS child_id,
        childname.ConceptName as child_label
    FROM
        Group parent RIGHT OUTER JOIN 
        Group child ON child.parent_id = parent.id
), 
jn AS 
(   
    SELECT
        parent_id,
        parent_label,
        child_id,
        child_label
    FROM
        org_name 
    WHERE
        parent_id = 5
    UNION ALL 
        SELECT
            C.parent_id,
            C.parent_label,
            C.child_id,
            C.child_label 
        FROM
            jn AS p JOIN 
            org_name AS C ON C.child_id = p.parent_id
) 
SELECT DISTINCT
    jn.parent_id,
    jn.parent_label,
    jn.child_id,
    jn.child_label
FROM
    jn 
ORDER BY
    1;

If you want to go down the hierarchy change the line:

org_name AS C ON C.child_id = p.parent_id

to

org_name AS C ON C.parent_id = p.child_id
EECOLOR

In plain SQL this would be tricky. You would have multiple options:

  1. Use a stored procedure to collect the correct records (recursively). Then convert those records into a tree using code
  2. Select all the records and convert those into a tree using code
  3. Use more advanced technique as described here (from Optimized SQL for tree structures) and here. Then convert those records into a tree using code

Depending on the way you want to do it in SQL you need to build a Slick query. The concept of Leaky Abstractions is very evident here.

So getting the tree structure requires two steps:

  1. Get the correct (or all records)
  2. Build (using regular code) a tree from those records

Since you are using Slick I don't think it's an option, but another database type might be a better fit for your data model. Check out NoSQL for the differences between the different types.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!