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

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, 当前未实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值