Accessing Relationships

You need to specify your DataMapper models $has_one and $has_many relationships before it is possible to access them. Read Setting up Relationships to see how.

If you haven't already, you should have read the Save and Delete topics to see how you save and delete relationships. I'll do a quick summary now to setup the example of accessing our relationships.


Let's use the following Models for our example:


class User extends DataMapper {

    var $has_one = array("country");

    function User()

/* End of file user.php */
/* Location: ./application/models/user.php */


class Country extends DataMapper {

    var $table = "countries";

    var $has_many = array("user");

    function Country()

/* End of file country.php */
/* Location: ./application/models/country.php */

Looking above, we can see that a user can relate to only one country but a country can relate to many users.

In a Controller

First we'll create some users:

Now a few groups:

With data to play around with, we'll get user Fred Smith and relate him to the Administrator group:

It's easy to add multiple relations as well. We'll add users Jayne Doe and Joe Public to the Member group:

Finally the Accessing

Now that we understand what our relationships currently are, we can look at how to access them.

To access a relationship, you use the singular name of the related object, in lowercase, as though it is a property of the current object. To demonstrate, we'll look at which group Fred is related to. From the user objects point of view we're expecting only one result so we can just grab all related groups.

As you can see, we populated the related object in the same way we do normal objects (read Get for more information) before accessing the values themselves. Now we'll look at which users are related to the Member Group. From the groups point of view, there may be one or more users. We know it has 2 users since we added them. The related objects are fully functional DataMapper objects. You can do all the usual get, save and delete actions on them. Since we expect multiple related objects, we'll use the related all list.

You can dig as deep as you want with the related items. For example:

I highly recommend you checkout the Usage Examples as they go into further depth on Accessing Relationships.