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.

Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • If you've built your database properly, you won't be able to delete the post until all it's dependent records (comments and logs in this case) have been removed. You'll have to break referential integrity to allow logs to remain when you delete the post. – RichardAtHome Sep 26 '12 at 16:14
  • That's the problem I'm having yeah. – Alvaro Sep 27 '12 at 08:59

3 Answers3

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.

adriaroca
  • 172
  • 11
Borislav Sabev
  • 4,776
  • 1
  • 24
  • 30
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.)

petervaz
  • 13,685
  • 1
  • 15
  • 15
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.

RichardAtHome
  • 4,293
  • 4
  • 20
  • 29