Defining and using one-to-many associations

A type of record is marked with a one-to-many association if one of its property define a "belongs_to" property in the "meta_field" array.

Faculatively, one the other side of the relation, it is also possible to define a property with an "has_many" key and get more methods.

Methods available with the "belongs_to" property

Methods available with the "has_many" property

Quick exemple

Let's consider two types of records: files and file formats. Each record of type "File" may be given one and only one "Format" (being ".gif", ".txt", ".php", ...).

The key while defining this sort of relationship is the proper usage of the "belongs_to" keyword.

In our exemple, a file belongs to a type of format, meaning a new property in "File" shall be defined with the property "belongs_to".

Using optional Porte naming conventions, an array identified by the key "format" will be added to the "meta_fields" array of the File objects, and its value will be an array containing the key "belongs_to" set to true.

In such a case, Porte will automatically look for a class "Format" and hook up each new file objects with a new set of methods to access/define/modify their associated format.

Moreover, format objects may also recieve a new set of methods. To achieve this, using optional Porte naming conventions, an array identified by the key "files" (notice the plurality) will be added to the "meta_fields" array of the Format objects.

Using the belongs_to property


class File extends PorteRecord{
  $meta_fields = array(
    'format' => array( 'belongs_to' )
  );
}

class Format extends PorteRecord{
  $meta_fields = array(
    'files' => array( 'has_many' )
  );
}

$file = new File();
$format = new Format();
$file->setFormat($format);
$file->save();
    

Setting up the "belongs_to" property

The following keys may be used:

Once a property is clean up by its model, the resulting config is:

Setting up the "has_many" property

The following keys may be used:

Once a property is clean up by its model, the resulting config is:

Open Source Object Relational Mapping in PHP

Download Porte 0.2.1