nested_set v0.0.2
NestedSet
#Implements nested sets
## In your Ecto model(ExShop.Category):
defmodule ExShop.Category do
use ExShop.Web, :model
# Specify
order_by_field: field by which we'll order result set
changeset: changeset method for updating tree
children_association: association name to get children
parent_id_column: column name storing the parent_id of the node
left_col: column name for storing node's left value
right_col: column name for storing node's right value
use NestedSet, order_by_field: :name, changeset: :nested_set_changeset, children_association: :children, parent_id_column: :parent_id, left_col: :lft, right_col: :rgt
schema "categories" do
field :lft, :integer, default: 0
field :rgt, :integer, default: 0
has_many :children, ExShop.Category, [foreign_key: :parent_id, on_delete: :delete_all]
belongs_to :parent, ExShop.Category, [foreign_key: :parent_id]
end
@required_fields ~w(name)
@optional_fields ~w(parent_id lft rgt)
# Nested Set expect a changeset like:
def nested_set_changeset(model, params ) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
# First get the model by:
model = ExShop.Repo.get_by(ExShop.Category, id: 35)
# Get descendent's count by:
ExShop.Category.descendents_count(model) #=> 3
# Get the descendants ordered by default field by:
ExShop.Category.descendants(model)
# Get the descendants ordered by default field by other field like id:
ExShop.Category.descendants(model, %{order_by_field: :id})
# Get the unordered descendants
ExShop.Category.descendants(model, %{ordered: :false})
# Get the ancestors ordered by default field by:
ExShop.Category.ancestors(model)
# Get the ancestors ordered by default field by other field like id:
ExShop.Category.ancestors(model, %{order_by_field: :id})
# Get the unordered ancestors
ExShop.Category.ancestors(model, %{ordered: :false})
# Get the self_and_descendants by:
ExShop.Category.self_and_descendants(model)
# Get the self_and_ancestors by:
ExShop.Category.self_and_ancestors(model)
# Get the ancestors_count by:
ExShop.Category.ancestors_count(model, ExShop.Repo)
# Get the self_and_siblings by:
ExShop.Category.self_and_siblings(model)
# Get the leaves by:
ExShop.Category.leaves(model)
# Recalculate lft and rgt values for tree, or sub tree by passing node and the lft value(default 1) of the node
ExShop.Category.recalculate_lft_rgt(model, ExShop.Repo)
ExShop.Category.recalculate_lft_rgt(model, ExShop.Repo, %{order_by_field: :name, lft: 5})
#Get root node:
ExShop.Category.get_root_node()