Search code examples
cakephpcakephp-2.0cakephp-2.1cascading-deletescakephp-2.2

Is it possible to custom the delete on cascade of CakePHP?


I have a table with logs related to the Post ones and i dont want its data to be deleted when i delete a Post.

In the other hand, i want to delete all the comments of the Post as well as other data.

I have been taking a look at the documentation but they dont say anything about it: http://book.cakephp.org/2.0/en/models/deleting-data.html

Thanks.


Solution

  • You can do this in at least two different ways.

    On is when you're calling $this->Post->delete($id, $cascade) the second parameter is a boolean that shows if the delete operation should also remove any associated records - such that depend on a Post record:

    $this->Post->delete($id, false);
    

    Will not delete any associated records. This is also true for $this->Model->deleteAll();This is when you want to set it not globally.

    Depends is very important because this concept could also be set in the configuration of a hasMany or hasOne relation so that this is the default deletion behaveour:

    public $hasMany = array(
        'Log' => array(
            'className' => 'Log',
            'foreignKey' => 'post_id',
            'dependent' => false
        )
    );
    

    In this example, Log records will NOT be deleted when their associated Post record has been deleted.