Search code examples
zend-frameworkzend-dbzend-db-table

Zend DB relationships


I am creating an application in zend framework. Now i am stuck in the Zend table relationships.

I have 2 tables. I have set the primary key and the corresponding references in other tables. Now i want to join the two tables using the relationships (not with the join functions). Is it possible in zend?

the tables structures are like the one below

Schemetable

scheme_id primary key

Scheme_name

Scheme_Desc

Ratestable

rate_id

Scheme_id *foreign key ref scheme_id*

rates:

Time periods:

There is an one to many relation b/w the scheme and rates

I have done some coding in the model classes

Scheme.php

class Scheme extends Zend_Db_Table_Abstract {


 protected $_name = 'schemetable';

 protected $_dependentTables = array('rates');
}

Rates.php

class Rates extends Zend_Db_Table_Abstract {


 protected $_name = 'ratetable';

 protected $_referenceMap = array(
   'Scheme' => array(
   'columns' => array('scheme_id'),  
   'refColumns' => array('scheme_id'), 
   'refTableClass' => 'Scheme',  
  ),
 );
}

How can i fetch every scheme and their corresponding rates?

Thanks in advance.


Solution

  • Please, see the DOCS:

    http://framework.zend.com/manual/en/zend.db.table.relationships.html

    Fetching a Dependent Rowset

    If you have a Row object as the result of a query on a parent table, you can fetch rows from dependent tables that reference the current row. Use the method:

    $row->findDependentRowset($table);
    

    Example #4 Fetching Dependent Rowsets using the Magic Method

    This example shows finding dependent Rowsets equivalent to those in the previous examples. In this case, the application uses the magic method invocation instead of specifying the table and rule as strings.

      $accountsTable = new Accounts();
      $accountsRowset = $accountsTable->find(1234);
      $user1234 = $accountsRowset->current();
    
      // Use the default reference rule
      $bugsReportedBy = $user1234->findBugs();
    
      // Specify the reference rule
      $bugsAssignedTo = $user1234->findBugsByEngineer();
    

    Fetching a parent row

    If you have a Row object as the result of a query on a dependent table, you can fetch the row in the parent to which the dependent row refers. Use the method:

    $row->findParentRow($table);
    

    This example shows finding parent Rows equivalent to those in the previous examples. In this case, the application uses the magic method invocation instead of specifying the table and rule as strings.

      $bugsTable = new Bugs();
      $bugsRowset = $bugsTable->fetchAll(array('bug_status = ?', 'NEW'));
      $bug1 = $bugsRowset->current();
    
      // Use the default reference rule
      $reporter = $bug1->findParentAccounts();
    
      // Specify the reference rule
      $engineer = $bug1->findParentAccountsByEngineer();