Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp 3.x cascade delete not working

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

like image 677
Pavithra Avatar asked Jan 24 '26 06:01

Pavithra


1 Answers

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

like image 91
aavrug Avatar answered Jan 26 '26 23:01

aavrug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!