Created
October 3, 2014 13:59
-
-
Save taybin/16a30c08b73ae76a72be to your computer and use it in GitHub Desktop.
ecto get parents/children
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Node do | |
import Ecto.Query, only: [from: 2] | |
def get_children(node) do | |
from(n in Node, | |
join: n2n in NodeToNode, on: n.id == n2n.parent_id, | |
inner_join: n1 in Node, on: n1.id == n2n.child_id, | |
select: n1, | |
where: n.id == ^node.id) | |
|> Repo.all | |
end | |
def get_parents(node) do | |
from(n in Node, | |
join: n2n in NodeToNode, on: n.id == n2n.child_id, | |
inner_join: n1 in Node, on: n1.id == n2n.parent_id, | |
select: n1, | |
where: n.id == ^node.id) | |
|> Repo.all | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment