5.2. Model relationships
Relationships between your Models are defined using the ModelRelation::define() method. For example:
ModelRelation::define('Person(1):Pet(M)');
ModelRelation::define('Book(M):Author(M)');
ModelRelation::define('Category(M):CategoryLinks.left_id.right_id(1):Category(M)');
See the API documentation for more details on the complexities of this powerful function.
1:M
Definition examples:
ModelRelation::define('House(1):Window(M)'); /* Presumes "window.house_id" FK */
ModelRelation::define('Human(1):Limb.person_id(M)'); /* Specifies "limb.person_id" FK */
ModelRelation::define('Category(1):Product(M)', 'nocascade'); /* Prevents cascading delete */
ModelRelation::define('Category(1):Category(M)'); /* A recursive relationship. See related section below. */
Read/write examples:
$house = Model::create('House');
$window = Model::create('Window');
$house->addRelatedModel($window);
/* For a recursive relationship */
$catA = Model::create('Category');
$catB = Model::create('Category');
$catA->addRelatedModel($catB); /* $catB becomes a child of $catA */
$catB->addRelatedModel($catA, ModelRelation::REF_CHILD); /* Same as above, but indicating "Set $catA as $catB's parent" */
M:1
Definition examples:
ModelRelation::define('Leaf(M):Tree(1)');
Read/write examples:
$leaf = Model::create('Leaf');
$tree = Model::create('Tree');
$leaf->addRelatedModel($tree);
M:M
Many-to-many relationships are actually defined internally within Buan as 1:M:1 relationships. The "M" in this relationship is the linking Model that joins the two "1" Models together.
Furthermore, this relationship is further broken down into two sub-relationships; a 1:M and a M:1.
Definition examples:
ModelRelation::define('Book(M):Author(M)'); /* Presumes linking model "BookAuthor" with FKs "book_id" and "author_id" */
ModelRelation::define('Friend(1):Mates.left_id.right_id(M):Friend(1)'); /* Recursive relationship, "Mates" is linking Model */
Read/write examples:
Recursive relationships
As shown above, Buan handles recursive relationships by means of relationship references.
In a typical 1:M relationship you have a parent (the "1") and a child (the "M").