Skip to content
javis edited this page Mar 21, 2012 · 2 revisions

Relationships

Relationships between objects can be categorized in 2 types: parents and childs.

Parent

A Parent relation should be used when you have one model that belongs to another. For example, a Child model belongs to a Parent or a Flag model belongs to a Country. The parent relation must be set in order to establish the relation between objects (it's required). This is done creating a property on the child object pointing to the parent object. In the parent object, the property pointing to the childs objects is not required, but optional.

Example: Lets say you have a Post model, this is how you relate it with the User model:

/**
 * type: User # here we set the classname of our parent object
 * relationship:
 *  type: parent
 */
public $author;

The Mapper class will then create the foreing key to the User table on the database. To access the user model, you would use $post->author.

Accessing parent properties on SQL conditions

When specifing SQL conditions for loading models, you can access to your parents properties as following:

$posts = Mapper::get('Post'," author.name like 'Javier' ");

There's not limit on how many parents properties inside parents can be accessed this way. Mapper will recognize the properties names used and create the SQL JOINS automatically.

Childs

Childs (has many) relationship will likely fall on the other side of a parent relationship. In the above examples, a post belongs to a user. From the user's perspective, a user has many posts. A has_many relationship is defined below:

/**
 * type: Post
 * relationship:
 *  type: childs
 *  inverse_property: author
 */
public $posts;

When deffining childs properties, you must specify the inverse_property attribute, which is the name of the property on the child model, that points to the parent.

To access to the Post models, you would user $user->posts, being $posts an array of objects.

Parameterizing childs properties return

Lets say you want to get your array of child models in a different order, or filtering them with a SQL condition. You can do this using your child property as a function. Following the avobe example, you would order them as following:

$user->posts($conditions=null, $order_by='title asc');

This dynamic new method on your models support the following arguments:

Model::child_relation($conditions=null, $order_by=null, $limit = null, $offset = 0);

Lazy Loading

By default, relationships are not loaded until you need to access to the object property for the first time. This behavior is called Lazy Loading, and can be disabled setting up the lazy_load attribute to false as shown below:

/**
 * type: Post
 * relationship:
 *  type: childs
 *  inverse_property: author
 *  lazy_load: false # set lazy loading to false.
 */
public $posts;
Clone this wiki locally