Anyone have thoughts on self referential linking / hierarchies for objects? ex: object 1 → object 2 → object 2 → object 3
This pattern is commonly implemented. The key is to maintain a clear naming convention for links, ensuring you always understand what type of relationship you’re traversing.
For example, if you have an Employee object with a property manager_id
, you could create a one-to-many link from Employee to Employee (assuming employees have only one manager) to establish that relationship.
- On the
“one”
side of the link, you would name it some variation ofEmployee Manager
with a similar API name. For instance: eachEmployee
has oneEmployee Manager
. - On the
“many”
side of the link, you would name it some variation ofDirect Report Employee
with a similar API name. For instance: eachEmployee Manager
has manyDirect Report Employee
(s).
This distinction is important when writing functions or performing any kind of link traversal query. It allows you to know which side of the relationship you’re targeting. For a given Employee, you can search around for their manager or search for their direct reports, and the objects that would be returned would be of type Employee.
I’ve done this with categories and it works fairly well. For example, I have a category ‘Groceries’ with it’s own category_id. I have another field on the object called group_category_id that references it’s hierarchical group. So, in both directions, ‘Groceries’ has a group_category_id for ‘Home’ purchases, and ‘Groceries’ also has sub categories (e.g. ‘Food’) whose group_category_id is equal to ‘Groceries’.