bsw@241: Unit = mondelefant.new_class() bsw@241: Unit.table = 'unit' bsw@241: bsw@241: Unit:add_reference{ bsw@241: mode = '1m', bsw@241: to = "Area", bsw@241: this_key = 'id', bsw@241: that_key = 'unit_id', bsw@241: ref = 'areas', bsw@241: back_ref = 'unit' bsw@241: } bsw@241: bsw@281: Unit:add_reference{ bsw@281: mode = 'mm', bsw@281: to = "Member", bsw@281: this_key = 'id', bsw@281: that_key = 'id', bsw@281: connected_by_table = 'privilege', bsw@281: connected_by_this_key = 'unit_id', bsw@281: connected_by_that_key = 'member_id', bsw@281: ref = 'members' bsw@281: } bsw@281: bsw@286: function recursive_add_child_units(units, parent_unit) bsw@286: parent_unit.childs = {} bsw@286: for i, unit in ipairs(units) do bsw@286: if unit.parent_id == parent_unit.id then bsw@286: parent_unit.childs[#(parent_unit.childs)+1] = unit bsw@286: recursive_add_child_units(units, unit) bsw@286: end bsw@286: end bsw@286: end bsw@286: bsw@286: function recursive_get_child_units(units, parent_unit, depth) bsw@286: for i, unit in ipairs(parent_unit.childs) do bsw@286: unit.depth = depth bsw@286: units[#units+1] = unit bsw@286: recursive_get_child_units(units, unit, depth + 1) bsw@286: end bsw@286: end bsw@241: bsw@286: function Unit:get_flattened_tree() bsw@286: local units = Unit:new_selector():add_order_by("name"):exec() bsw@286: local unit_tree = {} bsw@286: for i, unit in ipairs(units) do bsw@286: if not unit.parent_id then bsw@286: unit_tree[#unit_tree+1] = unit bsw@286: recursive_add_child_units(units, unit) bsw@286: end bsw@286: end bsw@286: local depth = 1 bsw@286: local units = {} bsw@286: for i, unit in ipairs(unit_tree) do bsw@286: unit.depth = depth bsw@286: units[#units+1] = unit bsw@286: recursive_get_child_units(units, unit, depth + 1) bsw@286: end bsw@286: return units bsw@241: end