加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Elixir Ecto: 使用Arbor在Postgresql中实现邻接列表与树的遍历

发布时间:2020-12-13 17:01:11 所属栏目:百科 来源:网络整理
导读:Arbor 项目地址 什么是CTEs? 使用CTEs实现Ecto的邻接列表与树的遍历. Arbor 使用 parent_id 和 CTEs 创建简单的树状结构. 使用 defmodule Comment do use Ecto.Schema # See config options below use Arbor.Tree,foreign_key_type: :binary_id schema "comm

Arbor 项目地址

什么是CTEs?

使用CTEs实现Ecto的邻接列表与树的遍历. Arbor 使用 parent_idCTEs创建简单的树状结构.

使用

defmodule Comment do
  use Ecto.Schema
  # See config options below
  use Arbor.Tree,foreign_key_type: :binary_id

  schema "comments" do
    field :body,:string
    belongs_to :parent,Arbor.Comment

    timestamps
  end  
end

获取根级节点

roots = Comment.roots 
        |> Repo.all

获取兄弟节点

siblings = my_comment
        |> Comment.siblings
        |> Comment.order_by_popularity
        |> Repo.all

获取祖先节点

获取当前节点的先辈节点,从下网上返回所有父辈节点. 主要用于显示一个分类导航路径(类似网站的Breadcrumbs面包屑功能)

descendants = my_comment
              |> Comment.ancestors
              |> Comment.order_by_inserted_at
              |> Repo.all

获取后代节点

获取当前节点的所有后代节点,返回后代节点列表

descendants = my_comment
              |> Comment.descendants
              |> Comment.order_by_inserted_at
              |> Repo.all

获取子节点

获取当前节点的所有子节点

children = my_comment
           |> Comment.children
           |> Repo.all

获取父节点

获取当前节点的父节点

parent = my_comment
         |> Comment.parent
         |> Repo.first

选项

  • table_name 设置在CTEs中要使用的表名称

  • tree_name 设置CTE的名称

  • primary_key 默认来自于Ecto的@primary_key模块属性

  • primary_key_type 默认来自于Ecto的@primary_key模块属性

  • foreign_key 默认为parent_id

  • foreign_key_type 默认来自于Ecto的@primary_key模块属性

  • orphan_strategy 默认为 :nothing,当前未实现

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读