1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.db.table.relationships">
4 <title>Zend_Db_Table Relationships</title>
6 <sect2 id="zend.db.table.relationships.introduction">
7 <title>Introduction</title>
10 Tables have relationships to each other in a relational database. An entity in one
11 table can be linked to one or more entities in another table by using referential
12 integrity constraints defined in the database schema.
16 The <classname>Zend_Db_Table_Row</classname> class has methods for querying related rows
21 <sect2 id="zend.db.table.relationships.defining">
22 <title>Defining Relationships</title>
25 Define classes for each of your tables, extending the abstract class
26 <classname>Zend_Db_Table_Abstract</classname>, as described in
27 <link linkend="zend.db.table.defining">this chapter</link>. Also see
28 <link linkend="zend.db.adapter.example-database">this chapter</link> for a description
29 of the example database for which the following example code is designed.
33 Below are the <acronym>PHP</acronym> class definitions for these tables:
36 <programlisting language="php"><![CDATA[
37 class Accounts extends Zend_Db_Table_Abstract
39 protected $_name = 'accounts';
40 protected $_dependentTables = array('Bugs');
43 class Products extends Zend_Db_Table_Abstract
45 protected $_name = 'products';
46 protected $_dependentTables = array('BugsProducts');
49 class Bugs extends Zend_Db_Table_Abstract
51 protected $_name = 'bugs';
53 protected $_dependentTables = array('BugsProducts');
55 protected $_referenceMap = array(
57 'columns' => 'reported_by',
58 'refTableClass' => 'Accounts',
59 'refColumns' => 'account_name'
62 'columns' => 'assigned_to',
63 'refTableClass' => 'Accounts',
64 'refColumns' => 'account_name'
67 'columns' => array('verified_by'),
68 'refTableClass' => 'Accounts',
69 'refColumns' => array('account_name')
74 class BugsProducts extends Zend_Db_Table_Abstract
76 protected $_name = 'bugs_products';
78 protected $_referenceMap = array(
80 'columns' => array('bug_id'),
81 'refTableClass' => 'Bugs',
82 'refColumns' => array('bug_id')
85 'columns' => array('product_id'),
86 'refTableClass' => 'Products',
87 'refColumns' => array('product_id')
95 If you use <classname>Zend_Db_Table</classname> to emulate cascading
96 <constant>UPDATE</constant> and <constant>DELETE</constant>
97 operations, declare the <varname>$_dependentTables</varname> array in the class for the
98 parent table. List the class name for each dependent table. Use the class name, not the
99 physical name of the <acronym>SQL</acronym> table.
104 Skip declaration of <varname>$_dependentTables</varname> if you use referential
105 integrity constraints in the <acronym>RDBMS</acronym> server to implement cascading
106 operations. See <link linkend="zend.db.table.relationships.cascading">this
107 chapter</link> for more information.
112 Declare the <varname>$_referenceMap</varname> array in the class for each dependent
113 table. This is an associative array of reference "rules". A reference rule identifies
114 which table is the parent table in the relationship, and also lists which columns in the
115 dependent table reference which columns in the parent table.
119 The rule key is a string used as an index to the <varname>$_referenceMap</varname>
120 array. This rule key is used to identify each reference relationship. Choose a
121 descriptive name for this rule key. It's best to use a string that can be part of a
122 <acronym>PHP</acronym> method name, as you will see later.
126 In the example <acronym>PHP</acronym> code above, the rule keys in the Bugs table class
127 are: <command>'Reporter'</command>, <command>'Engineer'</command>,
128 <command>'Verifier'</command>, and <command>'Product'</command>.
132 The value of each rule entry in the <varname>$_referenceMap</varname> array is also an
133 associative array. The elements of this rule entry are described below:
139 <emphasis>columns</emphasis> => A string or an array of strings
140 naming the foreign key column names in the dependent table.
144 It's common for this to be a single column, but some tables have multi-column
151 <emphasis>refTableClass</emphasis> => The class name of the parent table. Use
152 the class name, not the physical name of the <acronym>SQL</acronym> table.
156 It's common for a dependent table to have only one reference to its parent
157 table, but some tables have multiple references to the same parent table. In
158 the example database, there is one reference from the <command>bugs</command>
159 table to the <command>products</command> table, but three references from the
160 <command>bugs</command> table to the <command>accounts</command> table. Put each
161 reference in a separate entry in the <varname>$_referenceMap</varname> array.
167 <emphasis>refColumns</emphasis> => A string or an array of
168 strings naming the primary key column names in the parent table.
172 It's common for this to be a single column, but some tables have multi-column
173 keys. If the reference uses a multi-column key, the order of columns in the
174 <command>'columns'</command> entry must match the order of columns in the
175 <command>'refColumns'</command> entry.
179 It is optional to specify this element. If you don't specify the
180 <property>refColumns</property>, the columns reported as the primary key columns
181 of the parent table are used by default.
187 <emphasis>onDelete</emphasis> => The rule for an action to
188 execute if a row is deleted in the parent table. See
189 <link linkend="zend.db.table.relationships.cascading">this chapter</link> for
196 <emphasis>onUpdate</emphasis> => The rule for an action to
197 execute if values in primary key columns are updated in the parent table. See
198 <link linkend="zend.db.table.relationships.cascading">this chapter</link> for
205 <sect2 id="zend.db.table.relationships.fetching.dependent">
206 <title>Fetching a Dependent Rowset</title>
209 If you have a Row object as the result of a query on a parent table, you can fetch rows
210 from dependent tables that reference the current row. Use the method:
213 <programlisting language="php"><![CDATA[
214 $row->findDependentRowset($table, [$rule]);
218 This method returns a <classname>Zend_Db_Table_Rowset_Abstract</classname> object,
219 containing a set of rows from the dependent table <varname>$table</varname> that refer
220 to the row identified by the <varname>$row</varname> object.
224 The first argument <varname>$table</varname> can be a string that specifies the
225 dependent table by its class name. You can also specify the dependent table by using an
226 object of that table class.
229 <example id="zend.db.table.relationships.fetching.dependent.example">
230 <title>Fetching a Dependent Rowset</title>
233 This example shows getting a Row object from the table <command>Accounts</command>,
234 and finding the <command>Bugs</command> reported by that account.
237 <programlisting language="php"><![CDATA[
238 $accountsTable = new Accounts();
239 $accountsRowset = $accountsTable->find(1234);
240 $user1234 = $accountsRowset->current();
242 $bugsReportedByUser = $user1234->findDependentRowset('Bugs');
247 The second argument <varname>$rule</varname> is optional. It is a string that names the
248 rule key in the <varname>$_referenceMap</varname> array of the dependent table class. If
249 you don't specify a rule, the first rule in the array that references the parent table
250 is used. If you need to use a rule other than the first, you need to specify the key.
254 In the example code above, the rule key is not specified, so the rule used by default
255 is the first one that matches the parent table. This is the rule
256 <command>'Reporter'</command>.
259 <example id="zend.db.table.relationships.fetching.dependent.example-by">
260 <title>Fetching a Dependent Rowset By a Specific Rule</title>
263 This example shows getting a Row object from the table <command>Accounts</command>,
264 and finding the <command>Bugs</command> assigned to be fixed by the user of that
265 account. The rule key string that corresponds to this reference relationship in this
266 example is <command>'Engineer'</command>.
269 <programlisting language="php"><![CDATA[
270 $accountsTable = new Accounts();
271 $accountsRowset = $accountsTable->find(1234);
272 $user1234 = $accountsRowset->current();
274 $bugsAssignedToUser = $user1234->findDependentRowset('Bugs', 'Engineer');
279 You can also add criteria, ordering and limits to your relationships using the parent
283 <example id="zend.db.table.relationships.fetching.dependent.example-by-select">
284 <title>Fetching a Dependent Rowset using a Zend_Db_Table_Select</title>
287 This example shows getting a Row object from the table
288 <command>Accounts</command>, and finding the <command>Bugs</command> assigned to
289 be fixed by the user of that account, limited only to 3 rows and ordered by
293 <programlisting language="php"><![CDATA[
294 $accountsTable = new Accounts();
295 $accountsRowset = $accountsTable->find(1234);
296 $user1234 = $accountsRowset->current();
297 $select = $accountsTable->select()->order('name ASC')
300 $bugsAssignedToUser = $user1234->findDependentRowset('Bugs',
307 Alternatively, you can query rows from a dependent table using a special mechanism
308 called a "magic method". <classname>Zend_Db_Table_Row_Abstract</classname> invokes the
309 method: <methodname>findDependentRowset('<TableClass>',
310 '<Rule>')</methodname> if you invoke a method on the Row object matching
311 either of the following patterns:
317 <command>$row->find<TableClass>()</command>
323 <command>$row->find<TableClass>By<Rule>()</command>
329 In the patterns above, <command><TableClass></command> and
330 <command><Rule></command> are strings that correspond to the class name of the
331 dependent table, and the dependent table's rule key that references the parent table.
336 Some application frameworks, such as Ruby on Rails, use a mechanism called
337 "inflection" to allow the spelling of identifiers to change depending on usage. For
338 simplicity, <classname>Zend_Db_Table_Row</classname> does not provide any inflection
339 mechanism. The table identity and the rule key named in the method call must match
340 the spelling of the class and rule key exactly.
344 <example id="zend.db.table.relationships.fetching.dependent.example-magic">
345 <title>Fetching Dependent Rowsets using the Magic Method</title>
348 This example shows finding dependent Rowsets equivalent to those in the previous
349 examples. In this case, the application uses the magic method invocation instead of
350 specifying the table and rule as strings.
353 <programlisting language="php"><![CDATA[
354 $accountsTable = new Accounts();
355 $accountsRowset = $accountsTable->find(1234);
356 $user1234 = $accountsRowset->current();
358 // Use the default reference rule
359 $bugsReportedBy = $user1234->findBugs();
361 // Specify the reference rule
362 $bugsAssignedTo = $user1234->findBugsByEngineer();
367 <sect2 id="zend.db.table.relationships.fetching.parent">
368 <title>Fetching a Parent Row</title>
371 If you have a Row object as the result of a query on a dependent table, you can fetch
372 the row in the parent to which the dependent row refers. Use the method:
375 <programlisting language="php"><![CDATA[
376 $row->findParentRow($table, [$rule]);
380 There always should be exactly one row in the parent table referenced by a dependent
381 row, therefore this method returns a Row object, not a Rowset object.
385 The first argument <varname>$table</varname> can be a string that specifies the parent
386 table by its class name. You can also specify the parent table by using an object of
390 <example id="zend.db.table.relationships.fetching.parent.example">
391 <title>Fetching the Parent Row</title>
394 This example shows getting a Row object from the table <command>Bugs</command> (for
395 example one of those bugs with status 'NEW'), and finding the row in the
396 <command>Accounts</command> table for the user who reported the bug.
399 <programlisting language="php"><![CDATA[
400 $bugsTable = new Bugs();
401 $bugsRowset = $bugsTable->fetchAll(array('bug_status = ?' => 'NEW'));
402 $bug1 = $bugsRowset->current();
404 $reporter = $bug1->findParentRow('Accounts');
409 The second argument <varname>$rule</varname> is optional. It is a string that names the
410 rule key in the <varname>$_referenceMap</varname> array of the dependent table class. If
411 you don't specify a rule, the first rule in the array that references the parent table
412 is used. If you need to use a rule other than the first, you need to specify the key.
416 In the example above, the rule key is not specified, so the rule used by default is the
417 first one that matches the parent table. This is the rule <command>'Reporter'</command>.
420 <example id="zend.db.table.relationships.fetching.parent.example-by">
421 <title>Fetching a Parent Row By a Specific Rule</title>
424 This example shows getting a Row object from the table <command>Bugs</command>, and
425 finding the account for the engineer assigned to fix that bug. The rule key string
426 that corresponds to this reference relationship in this example is
427 <command>'Engineer'</command>.
430 <programlisting language="php"><![CDATA[
431 $bugsTable = new Bugs();
432 $bugsRowset = $bugsTable->fetchAll(array('bug_status = ?', 'NEW'));
433 $bug1 = $bugsRowset->current();
435 $engineer = $bug1->findParentRow('Accounts', 'Engineer');
440 Alternatively, you can query rows from a parent table using a "magic method".
441 <classname>Zend_Db_Table_Row_Abstract</classname> invokes the method:
442 <methodname>findParentRow('<TableClass>', '<Rule>')</methodname> if you
443 invoke a method on the Row object matching either of the following patterns:
449 <command>$row->findParent<TableClass>([Zend_Db_Table_Select
456 <command>$row->findParent<TableClass>By<Rule>([Zend_Db_Table_Select
463 In the patterns above, <command><TableClass></command> and
464 <command><Rule></command> are strings that correspond to the class name of the
465 parent table, and the dependent table's rule key that references the parent table.
470 The table identity and the rule key named in the method call must match the
471 spelling of the class and rule key exactly.
475 <example id="zend.db.table.relationships.fetching.parent.example-magic">
476 <title>Fetching the Parent Row using the Magic Method</title>
479 This example shows finding parent Rows equivalent to those in the previous
480 examples. In this case, the application uses the magic method invocation instead of
481 specifying the table and rule as strings.
484 <programlisting language="php"><![CDATA[
485 $bugsTable = new Bugs();
486 $bugsRowset = $bugsTable->fetchAll(array('bug_status = ?', 'NEW'));
487 $bug1 = $bugsRowset->current();
489 // Use the default reference rule
490 $reporter = $bug1->findParentAccounts();
492 // Specify the reference rule
493 $engineer = $bug1->findParentAccountsByEngineer();
498 <sect2 id="zend.db.table.relationships.fetching.many-to-many">
499 <title>Fetching a Rowset via a Many-to-many Relationship</title>
502 If you have a Row object as the result of a query on one table in a many-to-many
503 relationship (for purposes of the example, call this the "origin" table), you can
504 fetch corresponding rows in the other table (call this the "destination" table) via an
505 intersection table. Use the method:
508 <programlisting language="php"><![CDATA[
509 $row->findManyToManyRowset($table,
513 [Zend_Db_Table_Select $select]
519 This method returns a <classname>Zend_Db_Table_Rowset_Abstract</classname> containing
520 rows from the table <varname>$table</varname>, satisfying the many-to-many relationship.
521 The current Row object <varname>$row</varname> from the origin table is used to find
522 rows in the intersection table, and that is joined to the destination table.
526 The first argument <varname>$table</varname> can be a string that specifies the
527 destination table in the many-to-many relationship by its class name. You can also
528 specify the destination table by using an object of that table class.
532 The second argument <varname>$intersectionTable</varname> can be a string that specifies
533 the intersection table between the two tables in the many-to-many relationship by
534 its class name. You can also specify the intersection table by using an object of that
538 <example id="zend.db.table.relationships.fetching.many-to-many.example">
539 <title>Fetching a Rowset with the Many-to-many Method</title>
542 This example shows getting a Row object from the origin table
543 <command>Bugs</command>, and finding rows from the destination table
544 <command>Products</command>, representing products related to that bug.
547 <programlisting language="php"><![CDATA[
548 $bugsTable = new Bugs();
549 $bugsRowset = $bugsTable->find(1234);
550 $bug1234 = $bugsRowset->current();
552 $productsRowset = $bug1234->findManyToManyRowset('Products',
558 The third and fourth arguments <varname>$rule1</varname> and <varname>$rule2</varname>
559 are optional. These are strings that name the rule keys in the
560 <varname>$_referenceMap</varname> array of the intersection table.
564 The <varname>$rule1</varname> key names the rule for the relationship from the
565 intersection table to the origin table. In this example, this is the relationship from
566 <command>BugsProducts</command> to <command>Bugs</command>.
570 The <varname>$rule2</varname> key names the rule for the relationship from the
571 intersection table to the destination table. In this example, this is the relationship
572 from <command>Bugs</command> to <command>Products</command>.
576 Similarly to the methods for finding parent and dependent rows, if you don't specify a
577 rule, the method uses the first rule in the <varname>$_referenceMap</varname> array that
578 matches the tables in the relationship. If you need to use a rule other than the first,
579 you need to specify the key.
583 In the example code above, the rule key is not specified, so the rules used by default
584 are the first ones that match. In this case, <varname>$rule1</varname> is
585 <command>'Reporter'</command> and <varname>$rule2</varname> is
586 <command>'Product'</command>.
589 <example id="zend.db.table.relationships.fetching.many-to-many.example-by">
590 <title>Fetching a Rowset with the Many-to-many Method By a Specific Rule</title>
593 This example shows geting a Row object from the origin table
594 <command>Bugs</command>, and finding rows from the destination table
595 <command>Products</command>, representing products related to that bug.
598 <programlisting language="php"><![CDATA[
599 $bugsTable = new Bugs();
600 $bugsRowset = $bugsTable->find(1234);
601 $bug1234 = $bugsRowset->current();
603 $productsRowset = $bug1234->findManyToManyRowset('Products',
610 Alternatively, you can query rows from the destination table in a many-to-many
611 relationship using a "magic method." <classname>Zend_Db_Table_Row_Abstract</classname>
612 invokes the method: <command>findManyToManyRowset('<TableClass>',
613 '<IntersectionTableClass>', '<Rule1>', '<Rule2>')</command> if you
614 invoke a method matching any of the following patterns:
620 <command>$row->find<TableClass>Via<IntersectionTableClass>
621 ([Zend_Db_Table_Select $select])</command>
627 <command>$row->find<TableClass>Via<IntersectionTableClass>By<Rule1>
628 ([Zend_Db_Table_Select $select])</command>
634 <command>$row->find<TableClass>Via<IntersectionTableClass>By<Rule1>And<Rule2>
635 ([Zend_Db_Table_Select $select])</command>
641 In the patterns above, <command><TableClass></command> and
642 <command><IntersectionTableClass></command> are strings that correspond to the
643 class names of the destination table and the intersection table, respectively.
644 <command><Rule1></command> and <command><Rule2></command> are strings that
645 correspond to the rule keys in the intersection table that reference the origin table
646 and the destination table, respectively.
651 The table identities and the rule keys named in the method call must match the
652 spelling of the class and rule key exactly.
656 <example id="zend.db.table.relationships.fetching.many-to-many.example-magic">
657 <title>Fetching Rowsets using the Magic Many-to-many Method</title>
660 This example shows finding rows in the destination table of a many-to-many
661 relationship representing products related to a given bug.
664 <programlisting language="php"><![CDATA[
665 $bugsTable = new Bugs();
666 $bugsRowset = $bugsTable->find(1234);
667 $bug1234 = $bugsRowset->current();
669 // Use the default reference rule
670 $products = $bug1234->findProductsViaBugsProducts();
672 // Specify the reference rule
673 $products = $bug1234->findProductsViaBugsProductsByBug();
678 <sect2 id="zend.db.table.relationships.cascading">
679 <title>Cascading Write Operations</title>
682 <title>Declare DRI in the database:</title>
685 Declaring cascading operations in <classname>Zend_Db_Table</classname> is intended
686 <emphasis>only</emphasis> for <acronym>RDBMS</acronym> brands that do not support
687 declarative referential integrity (<acronym>DRI</acronym>).
691 For example, if you use MySQL's MyISAM storage engine, or SQLite, these solutions
692 do not support <acronym>DRI</acronym>. You may find it helpful to declare the
693 cascading operations with <classname>Zend_Db_Table</classname>.
697 If your <acronym>RDBMS</acronym> implements <acronym>DRI</acronym> and the
698 ON <constant>DELETE</constant> and ON <constant>UPDATE</constant> clauses, you
699 should declare these clauses in your database schema, instead of using the cascading
700 feature in <classname>Zend_Db_Table</classname>. Declaring cascading
701 <acronym>DRI</acronym> rules in the <acronym>RDBMS</acronym> is better for database
702 performance, consistency, and integrity.
706 Most importantly, do not declare cascading operations both in the
707 <acronym>RDBMS</acronym> and in your <classname>Zend_Db_Table</classname> class.
712 You can declare cascading operations to execute against a dependent table when you
713 apply an <constant>UPDATE</constant> or a <constant>DELETE</constant> to a row in a
717 <example id="zend.db.table.relationships.cascading.example-delete">
718 <title>Example of a Cascading Delete</title>
721 This example shows deleting a row in the <command>Products</command> table, which is
722 configured to automatically delete dependent rows in the <command>Bugs</command>
726 <programlisting language="php"><![CDATA[
727 $productsTable = new Products();
728 $productsRowset = $productsTable->find(1234);
729 $product1234 = $productsRowset->current();
731 $product1234->delete();
732 // Automatically cascades to Bugs table
733 // and deletes dependent rows.
738 Similarly, if you use <constant>UPDATE</constant> to change the value of a primary key
739 in a parent table, you may want the value in foreign keys of dependent tables to be
740 updated automatically to match the new value, so that such references are kept up to
745 It's usually not necessary to update the value of a primary key that was generated by a
746 sequence or other mechanism. But if you use a <emphasis>natural key</emphasis> that may
747 change value occasionally, it is more likely that you need to apply cascading updates
752 To declare a cascading relationship in the <classname>Zend_Db_Table</classname>, edit
753 the rules in the <varname>$_referenceMap</varname>. Set the associative array keys
754 <command>'onDelete'</command> and <command>'onUpdate'</command> to the string 'cascade'
755 (or the constant <constant>self::CASCADE</constant>). Before a row is deleted from the
756 parent table, or its primary key values updated, any rows in the dependent table that
757 refer to the parent's row are deleted or updated first.
760 <example id="zend.db.table.relationships.cascading.example-declaration">
761 <title>Example Declaration of Cascading Operations</title>
764 In the example below, rows in the <command>Bugs</command> table are automatically
765 deleted if the row in the <command>Products</command> table to which they refer is
766 deleted. The <command>'onDelete'</command> element of the reference map entry is set
767 to <constant>self::CASCADE</constant>.
771 No cascading update is done in the example below if the primary key value in the
772 parent class is changed. The <command>'onUpdate'</command> element of the reference
773 map entry is <constant>self::RESTRICT</constant>. You can get the same result by
774 omitting the <command>'onUpdate'</command> entry.
777 <programlisting language="php"><![CDATA[
778 class BugsProducts extends Zend_Db_Table_Abstract
781 protected $_referenceMap = array(
783 'columns' => array('product_id'),
784 'refTableClass' => 'Products',
785 'refColumns' => array('product_id'),
786 'onDelete' => self::CASCADE,
787 'onUpdate' => self::RESTRICT
795 <sect3 id="zend.db.table.relationships.cascading.notes">
796 <title>Notes Regarding Cascading Operations</title>
799 <emphasis>Cascading operations invoked by <classname>Zend_Db_Table</classname> are
800 not atomic.</emphasis>
804 This means that if your database implements and enforces referential integrity
805 constraints, a cascading <constant>UPDATE</constant> executed by a
806 <classname>Zend_Db_Table</classname> class conflicts with the constraint, and
807 results in a referential integrity violation. You can use cascading
808 <constant>UPDATE</constant> in <classname>Zend_Db_Table</classname>
809 <emphasis>only</emphasis> if your database does not enforce that referential
810 integrity constraint.
814 Cascading <constant>DELETE</constant> suffers less from the problem of referential
815 integrity violations. You can delete dependent rows as a non-atomic action before
816 deleting the parent row that they reference.
820 However, for both <constant>UPDATE</constant> and <constant>DELETE</constant>,
821 changing the database in a non-atomic way also creates the risk that another
822 database user can see the data in an inconsistent state. For example, if you delete
823 a row and all its dependent rows, there is a small chance that another database
824 client program can query the database after you have deleted the dependent rows, but
825 before you delete the parent row. That client program may see the parent row with no
826 dependent rows, and assume this is the intended state of the data. There is no way
827 for that client to know that its query read the database in the middle of a change.
831 The issue of non-atomic change can be mitigated by using transactions to isolate
832 your change. But some <acronym>RDBMS</acronym> brands don't support transactions, or
833 allow clients to read "dirty" changes that have not been committed yet.
837 <emphasis>Cascading operations in <classname>Zend_Db_Table</classname> are invoked
838 only by <classname>Zend_Db_Table</classname>.</emphasis>
842 Cascading deletes and updates defined in your <classname>Zend_Db_Table</classname>
843 classes are applied if you execute the <methodname>save()</methodname> or
844 <methodname>delete()</methodname> methods on the Row class. However, if you update
845 or delete data using another interface, such as a query tool or another application,
846 the cascading operations are not applied. Even when using
847 <methodname>update()</methodname> and <methodname>delete()</methodname> methods
848 in the <classname>Zend_Db_Adapter</classname> class, cascading operations defined in
849 your <classname>Zend_Db_Table</classname> classes are not executed.
853 <emphasis>No Cascading <constant>INSERT</constant>.</emphasis>
857 There is no support for a cascading <constant>INSERT</constant>. You must insert a
858 row to a parent table in one operation, and insert rows to a dependent table in a