CakePHP 3 关联删除

4

我是CakePHP的新手,对关联等方面还不太了解。当我想要删除一个类别时,我也希望能删除与该类别相关联的能力。这是我的表模型:

CategoriesTable.php

class CategoriesTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->belongsToMany('Competences');
    }
}

CompetencesTable.php

class CompetencesTable extends Table
{
     public function initialize(array $config)
     {
        parent::initialize($config);

        $this->belongsToMany('Categories');
        $this->belongsToMany('CategoriesCompetences');
     }
}

CategoriesCompetencesTable.php

class CategoriesCompetencesTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->belongsTo('Categories');
        $this->hasMany('Competences');
    }
}

当我删除一个分类时,它会删除链接表中的行,但不会删除CompetenceTable中的能力。我知道我忘了什么,但无法想出是什么。
1个回答

1
我不确定为什么您在联结表中有一个 hasMany 关联到 Competences。有原因吗?它应该是 belongsTo。如果没有,请尝试在关联选项中设置 dependent => true 的 hasMany 关联。 请查看 hasMany() 文档。认真阅读整个页面是个好主意。
public function initialize(array $config)
{
    $this->hasMany('Competences', [
        'foreignKey' => 'article_id',
        'dependent' => true,
    ]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接