Cascade delete with Zend Framework | Using Reference Map and Dependent Tables

 In Database, PHP, Zend Framework

I was googling around to find a good way to delete row from a column and automatically cascade to parent table. After reading a lot of bullshit, found the solution with the code above:

My Unit Model (Unit.php)

<?php

class Unit extends Zend_Db_Table_Abstract

{

protected $_keys = array(‘id’,’addressId’);

protected $_name = ‘unit’;

protected $_sequence = true;

protected $_primary = ‘id’;

protected $_referenceMap = array(

‘Address’ => array(

‘columns’           => array(‘addressId’),

‘refTableClass’   => ‘Address’, // my address model name

‘refColumns’      => array(‘id’),

‘onDelete’          => self::CASCADE

)

);

}

And on my Address Model (Address.php) I have:

<?php

class Address_Model_Address extends ZLayer_Model_Abstract

{

protected $_keys = array(‘id’);

protected $_name = ‘address’;

protected $_primary = ‘id’;

protected $_sequence = true;

protected $_dependentTables = array(

‘Unit’

);

}

On my Controller (UnitController.php) delete method I call:

public function deleteAction()

{

if($this->_getParam(‘id’)) {

$db = $this->getFrontController()->getParam(‘bootstrap’)->getResource(‘db’);

$db->beginTransaction();

try {

$unit = new Unit();

$row = $unit->fetchRow($this->_getParam(‘id’));

$parent = $row->findParentRow(‘Address’)->delete();

$db->commit();

} catch (Exception $e) {

$db->rollBack();

}

}

}

Recent Posts
0