Richard Knop
Richard Knop

Reputation: 83695

Zend_Db_Table Cascade DELETE And UPDATE

I'm trying to achieve a cascading UPDATE and DELETE effect in a MyISAM database (similar effect as you can create in InnoDB tables with foreign keys). Two example tables:

Now when I delete a row in the albums table I would like Zend_Db_Table to automatically delete all related rows in the photos table. This is what I have in the albums table:

protected $_name = 'albums';

protected $_dependentTables = array(
    'Photos'
);

And I have this in the photos table:

protected $_name = 'photos';

protected $_referenceMap = array(
    'Album' => array(
        'columns' => array('album_id'),
        'refTableClass' => 'Albums',
        'refColumns' => array('id')
    )
);

Yes when I delete a row in the albums table, the photos from that album do not get removed.

This is how I'm removing the album:

public function remove($id)
{
    $where = $this->getAdapter()->quoteInto('id = ?', $id, 'INTEGER');
    return $this->delete($where);
}

Upvotes: 1

Views: 3879

Answers (1)

Akeem
Akeem

Reputation: 8227

You need to setup the cascade delete. So your reference map should be:

protected $_referenceMap = array(
'Album' => array(
    'columns' => array('album_id'),
    'refTableClass' => 'Albums',
    'refColumns' => array('id'),
    'onDelete' => self::CASCADE
));

See full description of cascading operations here: http://framework.zend.com/manual/en/zend.db.table.relationships.html#zend.db.table.relationships.cascading

NB Cascading operations are only triggered when functions called on the actual row of the results set (i.e. Zend_Db_Table_Row class). To trigger the delete function in this example:

$album = $albums->find($id);
$album->delete();//This triggers the cascading delete

Upvotes: 3

Related Questions