Skip to main content
Previous sectionNext section

Creating a Relationship

When we added addresses to the application, we added a simple property, Home, of type Address. We are going to do something somewhat different for phone numbers. We are going to create a relationship between the Contact and PhoneNumber classes.

More specifically, we are going to create a Parent-Child relationship with Contact as the parent and PhoneNumber as the child. The effect of this will be that each contact can contain several phone numbers while each phone number must be contained by a single contact. Moreover, deleting a contact automatically deletes all of the phone numbers that it contains.

When you create a parent-child relationship between a pair of classes, you add a new property to each of the classes. To the parent class, you add a collection of objects of the child class type. To the child class, you add a property that refers back to the parent class object.

Here are the steps for creating the relationship using the Add Property wizard. Note that you can also code the relationship by hand in the class editor if you prefer.

  1. Open Contact in Studio and launch the Add Property wizard. To launch the wizard, click Class–>Add–>Property (Same as before). On the Wizard's first screen assign the property the name PhoneNumbers. Click Next.

    images/tqks_relationship1_20111.png

  2. On the Property Type page, click Relationship. Click Next.

    images/tqks_relationship2_20111.png

  3. On the Relationship Characteristics page, specify the following:

    • This relationship property refers to: Children: This object's children

    • This relationship property references objects of the following type: ContactDB.PhoneNumber

    • The name of the corresponding property in the referenced class is: Contact. Note that this property does not appear on the drop-down list. You must type it into the box.

    • Click Next. This displays the Additional Changes screen.

    images/tqks_relationship3_20111.png

  4. On the Additional Changes page, leave the Create new property “Contact” in class ContactDB.PhoneNumber box selected. Click Finish.

    images/tqks_relationship4_20111.png

  5. The Wizard adds the following declarations to Contact and PhoneNumber:

    Contact

    Relationship PhoneNumbers As ContactDB.PhoneNumber 
      [ Cardinality = children, Inverse = Contact ];
    
    Copy code to clipboard

    PhoneNumber

    Relationship Contact As ContactDB.Contact 
        [ Cardinality = parent, Inverse = PhoneNumbers ];
    
    Copy code to clipboard
  6. Save and recompile both Contact and PhoneNumber.

Note:

For more information on relationships, read Relationships in Using Caché Objects.