Elixir Ecto: 使用Arbor在Postgresql中实现邻接列表与树的遍历
文章目录
什么是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 "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_idforeign_key_type默认来自于Ecto的@primary_key模块属性orphan_strategy默认为:nothing, 当前未实现
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论