php-activerecord icon indicating copy to clipboard operation
php-activerecord copied to clipboard

Add 'dependent' => 'destroy|delete' option to associations

Open jpfuentes2 opened this issue 15 years ago • 4 comments

Use rails behavior:

If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method.

jpfuentes2 avatar Aug 08 '10 16:08 jpfuentes2

Am I right?

<?php

class Foo extends \ActiveRecord\Model
{
    static $has_many = array(
        array('bars', 'dependent' => 'destroy'),
        array('eggs', 'dependent' => 'delete'),
    );
}

$foo = Foo::find(1);
$foo->delete();
// will actually perform something like this:
foreach ($foo->bars as &$bar) {
    $bar->delete();
}
Egg::delete_all(array('conditions' => array('foo_id' => $foo->id)));
$foo->delete();

greut avatar May 18 '11 17:05 greut

is your example above suppose to work or just for illustration purpose, because I can't find dependent anywhere in the codebase.

silentworks avatar Jun 27 '11 14:06 silentworks

@silentworks ditto. Somebody should add this. Maybe I will look into it if I keep using php activerecord for future projects.

zarazan avatar Jun 06 '13 00:06 zarazan

Definitely should add this, having a after_destroy callback in almost all of my models is kinda redundant;

class Column extends ActiveRecord\Model{
    static $after_destroy = array(
        'destroy_related_data'
    );

    public function destroy_related_data(){
        foreach($this->boxes as $_box){
            $_box->delete();
        }
    }
}

koenpunt avatar Jun 06 '13 08:06 koenpunt