CakePHP - 删除级联不起作用

tee*_*ink 3 cakephp

在CakePHP中,我有一个模型Type和SpecificType.

SpecificType属于Type.(type_id字段)

当我删除SpecificType的条目时,我怎么能删除Type?

我有它

$this->SpecificType->del($id, true)
Run Code Online (Sandbox Code Playgroud)

但是,Type下的条目不会被删除.

谢谢,
Tee

Hea*_*ota 8

我认为你不能删除Type with SpecificType cascade.如果有hasMany或HABTM关系,你只能使用cascade.

在手册中说.

删除$ id标识的记录.默认情况下,还会删除依赖于指定要删除的记录的记录.

例如,删除与许多配方记录(用户'hasMany'或'hasAndBelongsToMany'食谱)相关联的用户记录时:

* if $cascade is set to true, the related Recipe records are also
Run Code Online (Sandbox Code Playgroud)

如果models dependent-value设置为true,则删除.*如果$ cascade设置为false,则在删除用户后,配方记录将保留.

你总是可以跑

$this->del($id, true);
Run Code Online (Sandbox Code Playgroud)

删除具有相关SpecificType-s的Type.


Chu*_*ess 8

您想要删除Type,而不是SpecificType.您还需要确保为Type输入正确的模型:

var $hasMany = array(
    'SpecificType' => array(
    'className' => 'SpecificType',
    'foreignKey' => 'type_id',
    'dependent'=> true,
    )
);
Run Code Online (Sandbox Code Playgroud)

然后删除类型,它将工作.

如果要删除子项(SpecificType)并且要删除它的父项,则必须在父模型上调用delete.但请记住,如果您正确设置了Cascade(dependent = true在模型上),则SpecificType无论如何都会删除所有孩子.

注意:如果您要删除孩子的父母,您可能需要重新考虑您的关系并确认他们是正确的.如果你真的想要它们,那就不要对孩子进行删除.只需确保正确设置级联关系,拉出子级的父级信息,然后删除父级.然后所有的孩子也将被移除.