<< Click to Display Table of Contents >> One-to-many relationships |
|
Examples of one-to-many relationships include the relationships between
•A mother and her children
•A nation and its states or provinces. (Or a state and its counties. Or a county and its towns.)
•A company and its divisions. Or a company and its employees.
•A school and its students.
The goal of establishing one-to-many relationships in Ventity is so that the "one" entity can use in its equations information about the "many", while each of the "many" has access to information about the "one". So, a calculation in a state entity may need the total tax revenue across all its counties, while each county may need to know the tax rates set by the state.
The example available in the Sample Projects directory is the "one to many" model, which uses the context of a mother and her children. In this case, the mother and children are all the same type of entity (here, a Platypus), but the mechanics are similar if the "one" is of a different type than the "many".
There are four key pieces to forming the one-to-many relationship.
1. In general, each member of the "many" needs an attribute that refers to it's "one". In the example, the Platypus entity type has an attribute called "mother", which "Refers To" another platypus. That is, a Platypus' "mother" attribute is equal to its mother's PlatypusID. This forms half the link we need: any platypus now has access to its mother's information.
2. Next, we need to create a subcollection, partitioning the "many" by the value of that attribute. In the example, we create a collection of platypuses, partitioned by the value of the "mother" attribute.
3. Third, we need to create for the "one" a reference to its subcollection of "many". In the example, each platypus has a reference called "children", directed to the subcollection of platypuses whose mother's ID equals its own ID.
4. In initialization (or via create actions), each new entity of the "many" must specify the ID of its "one". In the example, we've populated the model with 16 platypuses, and for each one, we've entered the name of the mother.
With those pieces, information is available in both directions. Any platypus knows how many children it has through children.count.
As a bonus, we have established another reference, this one to the subcollection of platypuses whose mother is the same as the mother of the current platypus. The collection of platypuses whose mother is my mother is, of course, my siblings and myself, so we've called this reference "siblings and self".
The number of siblings of each platypus is thus one less than the count of siblings and self.