3

I have 3 tables names articles,comments,addresses.

articles -> fields(id,title,body)
comments -> fields(id,article_id,comment)
addresses-> fields(id,article_id,address)

and in my articles controller i have kept dependent=>true and also cascadeCallbacks=>true. First i tried with dependent => true,i dint work then added cascade, still it does not work. Below is my code.

    $this->hasMany('Comments', [
        'className' => 'Comments',
        'dependent' => true,
        'cascadeCallbacks' => true,
    ]);

    $this->hasOne('Addresses',[
        'dependent' => true,
        'cascadeCallbacks' => true,
    ]);

but while deleting articles, associated records are not deleted.

public function delete($id = null)
{
    $this->request->allowMethod(['post', 'delete']);
    $article = $this->Articles->get($id);
    if ($this->Articles->delete($article)) {
        $this->Flash->success(__('The article has been deleted.'));
    } else {
        $this->Flash->error(__('The article could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}

Please tell me what is the mistake i did. or any code need to be added or changed???? Pl help

Pavithra
  • 39
  • 4

1 Answers1

5

Try this : $this->hasMany('Comments', [ 'foreignKey' => 'article_id', 'dependent' => true, 'cascadeCallbacks' => true ]);

aavrug
  • 1,849
  • 1
  • 12
  • 20
  • Doesn't work for very deeply associated model. For example: `User->Plants->SpecialPlants` SpecialPlants records do not get deleted. – gdm Mar 17 '22 at 14:18