Previous Next

Modeling Many-to-Many Relationships

Modeling a many-to-many relationship between objects is simple: Each object manages a collection of the other kind. For example, consider the many-to-many relationship between employees and projects. To think of this relationship in objects, an Employee object has an array of Project objects representing all of the projects the employee works on; and a Project object has an array of Employee objects representing the people working on the project.

To model a many-to-many relationship in a database, you have to create an intermediate table (also known as a correlation or join table). For example, the database for employees and projects might have EMPLOYEE, PROJECT, and EMPLOYEE_PROJECT tables, where EMPLOYEE_PROJECT is the correlation table.

Given the relational database representation of a many-to-many relationship, how do you get the object model you want? You don’t want to see evidence of the correlation table in your object model, and you don’t want to write code to maintain database correlation rows. With Enterprise Objects, fortunately, you don’t have to. You can simply use flattened relationships to hide correlation tables.

A model with the following features has the effect of hiding the EMPLOYEE_PROJECT correlation table from its object model:

Consequently, EmployeeProject enterprise objects are never created, Employee objects have an array of related Projects, and Project objects have an array of related Employees. Furthermore, Enterprise Objects automatically manages rows in the EMPLOYEE_PROJECT correlation table.

Still, creating a model with the parameters described in this section would take quite a bit of work and would be error prone. Fortunately, EOModeler does all the work for you.

Follow these steps to create a many-to-many relationship between two entities:

  1. Switch to diagram view.
  2. Select the entities you want to join in a many-to-many relationship.

    Figure 5-11 Two entities before joining in a many-to-many relationship

    [image: ../Art/manytomanybefore.gif]
  3. Choose Join in Many-to-Many from the Property menu.

This creates a join table between the two entities, adds flattened relationships in the two entities, and sets the class property characteristic for the new relationship as described in this section. The two entities in Figure 5-11 when joined in a many-to-many relationship appear in the diagram view as shown in Figure 5-12.

Figure 5-12 Two entities after being joined in a many-to-many relationship

[image: ../Art/manytomanyafter.gif]

Previous Next


© 2002 Apple Computer, Inc. (Last Updated November 2002)