Search code examples
phpzend-frameworkdependencieszend-db

Zend find ALL dependent rows


Given example: "table->person" - "table->books"(uses->person_id) - "table->notebook"(uses->person_id)

In my Zend classes i define all relations from person to books and notebook and reverse. Now obviously if i want to delete that person, my application should make sure that this person no longer is in possession of anything (at least that's what i want to achieve).

Obviously with a small example i could check easily if $person->hasBooks() || $person->hasNotebooks() but as the database grows theres shoes and pants and glasses and lots of small stuff.

Is there ANY want to automate it in a way like

foreach ( connectedGoods in person as theGood) 
{
  if ( person->hasGood( theGood ) ) {
    //log person still uses theGood
  } 
} 

Or do i at all times have to manually check each "connectedGood"?

To Clarify: i do know how i can findDepentendRowset('singleTable') - i just wanna know if there's like a findDepentendRowset('allDependentTables')

Thanks in advance

//Edit Here is my current table structure to give a little more insight:

tbl_buildings:
b_id
b_*

tbl_asset_x
a_id
b_id (tbl_buildings)

tbl_asset_y
y_id
b_id (tbl_buildings)

Solution

  • If I understand you correctly, this should achieve your goals. I've added a method to the table row which checks each of its dependents.

    abstract class MyBaseTable extends Zend_Db_Table_Abstract {
        protected $_rowClass = 'MyBaseTableRow';
        public function getReferences() {
            return $this->_referenceMap;
        }
    }
    
    abstract class MyBaseTableRow extends Zend_Db_Table_Abstract {
        public function hasDependents() {
            foreach ($this->_getTable()->getReferences() as $entity => $info) {
                if (count($this->findDependentRowset($entity) > 0) {
                    return true;
                }
            }
            return false;
        }
    }
    
    class Persons extends MyBaseTable {
        protected $_referenceMap    = array(
            'Book' => array(
                'columns'           => 'reported_by',
                'refTableClass'     => 'Books',
                'refColumns'        => 'account_name'
            ),
            'Notebook' => array(
                'columns'           => 'assigned_to',
                'refTableClass'     => 'Notebooks',
                'refColumns'        => 'account_name'
            )
        );
    }
    
    $persons = new Persons();
    $person = $persons->find(1234);
    
    if ($person->hasDependents()) {
        echo 'freaking remove assets first';    
    } else {
        $person->delete();
    }
    

    Note: Untested!