Like a Train going down hill….

Standard
This post is over 11 years old and is probably out of date.

I have made some enhancements to Crtx_DB_DataObject this last week, one of which I really like.

One of the great things about ActiveRecord? is its handling of Relationships.

ActiveRecord? has this ability to specify that a record from a specific table belongs_to or that it is related to a number of other records in another table has_many. Furthermore, it supports lookup tables using has_and_belongs_to_many.

There are two things I don’t like about the way ActiveRecord? handles these relationships; First you must explicitly specify these relationships in the classes for these records (or rather, for the table) and secondly, the related records are loaded automatically.

Crtx_DB_DataObject gleans it knowledge of relationships from the columns in a record, and can therefore resolve these relationships automatically. An example is this:

Assuming a scheme where we have one Dog in a table called Dogs which is related to many Fleas in a table called Fleas using Fleas.Dog_id = Dog.id as a FK relationship.

  1.  
  2.  require_once Crtx/DB/DataObject.php;
  3.  
  4.  class Dog extends Crtx_DB_DataObject { }
  5.  
  6.  class Flea extends Crtx_DB_DataObject { }
  7.  
  8.  $dog = new Dog($dsn);
  9.  
  10.  $dog_record  = $dog->find(42);
  11.  
  12.  // has_many relationship, 1:*
  13.  $fleas = $dog_record->fleas() // Returns an array of fleas that have a Fleas.dog_id equal to $dog_record->id
  14.  
  15.  $flea = new Flea($dsn);
  16.  
  17.  $flea_record = $flea->find(457);
  18.  
  19.  // belongs_to relationship, 1:1
  20.  $dog = $flea_record->dog(); // Returns a single Record object for the related Dog, that is, where Dogs.id = $flea->Dog_id
  21.  ?>

Note the singular and plural of the dog() and

Truncated by Planet PHP, read more at the original (another 531 bytes)