2

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.

4

3 回答 3

2

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.

于 2012-09-27T06:59:21.733 回答
0

You can try removing the association before calling the delete using $this->Post->unbindModel('hasMany' => 'Log') (or $this->unbindModel('hasMany' => 'Log'inside Post model.)

于 2012-09-26T14:20:03.400 回答
0

If your back end is MySQL, you can switch off foreign key checks (SET FOREIGN_KEY_CHECKS=0;), remove the parent Post and its comments, and re-enable foreign key checks (SET FOREIGN_KEY_CHECKS=1;). I don't recommend this however.

I'd be inclined to implement a 'soft delete' on posts (give it a 'deleted' field and add an index to it which you set to true when it's deleted) and update your front end queries to ignore any posts with deleted = 1

There are a few soft delete behaviors out there but the code is pretty simple to implement.

于 2012-09-27T09:22:38.257 回答