Associations - sycobuny/pg_model GitHub Wiki
Associations
Summary
Associations are another name for foreign-key relationships. They allow you to dynamically load related objects based on a given object which has a declared association. Currently the implementation is fairly sparse, but it just means there's plenty of room for growth!
Declaring Associations
Associations must be declared with one of three functions, Model::one_to_many(), Model::many_to_one(), or Model::many_to_many(). They all feature the same three possible arguments: the associated class, the association name, and the class for which the association is being declared. An example, where one user has multiple possible registered accounts, would look like something like the following:
<?php
class Account extends Model { }
class User extends Model { }
Model::many_to_one('User', 'registered_user', 'Account');
Model::one_to_many('Account', 'accounts', 'User');
Using Associations
Associations, once declared, are retrieved using a method named after the association name given in the declaration. For our given example of accounts and registered users:
<?php
$id = $_GET['id'];
$user = new User();
$user->load($id);
$accounts = $user->load_accounts(); // $accounts is an array of Account objects
// ...OR!
$id = $_GET['id'];
$account = new Account();
$account->load($id);
$user = $account->load_user(); // $user is a single User object
Caching
Associations, after they are loaded, are cached. This means multiple calls to $user->load_accounts() will return the same array. Currently, reverse caching is not supported (that is, $account->load_user()->load_accounts() will return an array which has a different object). The caching can be overridden by supplying a true value to the load operation:
<?php
$user = $account->load_user();
$user_copy = $account->load_user(true); // a different object is returned.
Naming
Many-to-many associations use the two associated tables to construct a name for the third, a join table. It combines the two table names, in alphabetical order, with an underscore. For instance, if instead, accounts were allowed to have multiple users, it would be a many-to-many relationship and the join table name would be called accounts_users.
Limits
Amongst the biggest limits is that associations can not specify different table names (for many-to-many associations) or key values. They all default to a singular version of the table name, followed by _id. For instance, accounts in this example is expected to have a user_id field that references the id field in users. There is no accounting for multi-column primary keys, or even keys which are not named id.