Pergunta

Using cake 2.x I have 3 tables (I've shortened the names for this example removing the plural/singular cakephp conventions):

  1. Main (has many Sub1)
  2. Sub1 (belongs to main, hasmany Sub2)
  3. Sub2 (belongs to sub1)

When I delete a category from Main, all of its dependent sub1/sub2 items are properly deleted using $this->Main->delete($id, true) call.

However I'm not sure how to delete an item from Sub1 and remove all it's sub2 properties. The controller needs to manipulate all three levels of the tables. I tried:

$this->loadModel('Sub1');
$res = $this->Sub1->delete($id, true);

But it is not picking up the model bindings to Sub2 and deleting them. What is the proper convention for doing this kind of thing in cake and/or what am I doing wrong?

Foi útil?

Solução

There's two things I'd suggest checking:

1) check that dependent is set true for BOTH associations, that is, the $hasMany in Main, and the $hasMany in Sub1

2) check that 'exclusive' is NOT set to true in either of those associations. From the cookbook:

When exclusive is set to true, recursive model deletion does the delete with a deleteAll() call, instead of deleting each entity separately. This greatly improves performance, but may not be ideal for all circumstances.

If dependent is true, and exclusive is false, for both associations, then Cake should delete your associations recursively, as you can see from the source code.

Lastly, a couple of small tips to keep in mind, though they are unrelated to your current problem:

a)
In the code snippet you gave from your controller, you don't need to load the Sub1 model. It's already available. So you can call:

$res = $this->Main->Sub1->delete($id, true);

b) No need to pass in true as the second param in your delete method, because it's default value is already true. See http://book.cakephp.org/2.0/en/models/deleting-data.html

c) I obviously don't know what the specific differences are between your main, sub1 and sub2 models. But if they're essentially the same thing and you're just wanting to keep track of hierarchy, you should look into the Tree Behaviour

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top