@@ -114,31 +114,31 @@ defmodule MyApp.Employee.ManagedEmployees do
114
114
@impl true
115
115
@spec load ([Employee .t ()], keyword, map) ::
116
116
{: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
+
118
120
employee_ids = Enum .map (employees, & &1 .id)
119
121
120
122
all_descendants =
121
123
Employee
122
124
|> where ([l], l.manager_id in ^employee_ids )
123
125
|> recursive_cte_query (" employee_tree" , Employee )
124
126
|> Repo .all ()
125
- |> Map .new (fn employee ->
126
- {employee.id, employee}
127
- end )
127
+ |> Enum .group_by (& &1 .manager_id, & &1 )
128
128
129
129
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) })
132
132
|> then (& {:ok , &1 })
133
133
end
134
134
135
- defp with_descendants ([], _ ), do: []
135
+ defp with_descendants ([], _ , _ ), do: []
136
136
137
- defp with_descendants (employees, all_descendants) do
137
+ defp with_descendants (employees, all_descendants, relationship_name ) do
138
138
Enum .map (employees, fn employee ->
139
139
descendants = Map .get (all_descendants, employee.id, [])
140
140
141
- %{ employee | descendants: with_descendants (descendants, all_descendants)}
141
+ Map . put ( employee, relationship_name, with_descendants (descendants, all_descendants, relationship_name))
142
142
end )
143
143
end
144
144
0 commit comments