Using recursive CTE with Ecto

前端 未结 1 1785
花落未央
花落未央 2021-02-08 11:48

How would I go about using the result of a recursive CTE in a query I plan to run with Ecto? For example let\'s say I have a table, nodes, structured as so:

-- n         


        
相关标签:
1条回答
  • 2021-02-08 12:14

    I was able to accomplish this using a fragment. Here's an example of the code I used. I'll probably move this method to a stored procedure.

    Repo.all(MyProj.User,
      from u in MyProj.User,
      join: un in MyProj.UserNode, on: u.id == un.user_id,
      join: nt in fragment("""
      (
        WITH RECURSIVE node_tree AS (
          SELECT *
          FROM nodes
          WHERE nodes.id = ?
        UNION ALL
          SELECT n.*
          FROM nodes n
          INNER JOIN node_tree nt ON nt.parent_id == n.id
        )
      ) SELECT * FROM node_tree
      """, ^node_id), on: un.node_id == nt.id
    )
    
    0 讨论(0)
提交回复
热议问题