Skip to content

Commit c9269f6

Browse files
authored
docs: edit manual relationships example with group_by and relationship name (#542)
1 parent 6c67749 commit c9269f6

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

documentation/topics/advanced/manual-relationships.md

+9-9
Original file line numberDiff line numberDiff line change
@@ -114,31 +114,31 @@ defmodule MyApp.Employee.ManagedEmployees do
114114
@impl true
115115
@spec load([Employee.t()], keyword, map) ::
116116
{:ok, %{Ash.UUID.t() => [Employee.t()]}} | {:error, any}
117-
def load(employees, _opts, _context) do
117+
def load(employees, _opts, context) do
118+
relationship_name = context.relationship.name
119+
118120
employee_ids = Enum.map(employees, & &1.id)
119121

120122
all_descendants =
121123
Employee
122124
|> where([l], l.manager_id in ^employee_ids)
123125
|> recursive_cte_query("employee_tree", Employee)
124126
|> Repo.all()
125-
|> Map.new(fn employee ->
126-
{employee.id, employee}
127-
end)
127+
|> Enum.group_by(& &1.manager_id, & &1)
128128

129129
employees
130-
|> with_descendants(all_descendants)
131-
|> Map.new(&{&1.id, &1.descendants})
130+
|> with_descendants(all_descendants, relationship_name)
131+
|> Map.new(&{&1.id, Map.get(&1, relationship_name)})
132132
|> then(&{:ok, &1})
133133
end
134134

135-
defp with_descendants([], _), do: []
135+
defp with_descendants([], _, _), do: []
136136

137-
defp with_descendants(employees, all_descendants) do
137+
defp with_descendants(employees, all_descendants, relationship_name) do
138138
Enum.map(employees, fn employee ->
139139
descendants = Map.get(all_descendants, employee.id, [])
140140

141-
%{employee | descendants: with_descendants(descendants, all_descendants)}
141+
Map.put(employee, relationship_name, with_descendants(descendants, all_descendants, relationship_name))
142142
end)
143143
end
144144

0 commit comments

Comments
 (0)