问题
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
回答1:
Try this :
$this->hasMany('Comments', [
'foreignKey' => 'article_id',
'dependent' => true,
'cascadeCallbacks' => true
]);
来源:https://stackoverflow.com/questions/39148523/cakephp-3-x-cascade-delete-not-working