如果是自引用 belongsToMany 关联中的子项,则防止删除

Prevent deletion if is a child in a self-referencing belongsToMany association

在我的 ModelsTable 中,我有两个虚拟字段用于模型和另一个模型之间的自引用 belongsToMany 关联(子项是父项的附件,它可以有多个子项)使用 AccessoriesTable(使用 model_idaccessory_id 列)来执行 link.

$this->belongsToMany('AccessoryModels', [
    'className' => 'Models',
    'through' => 'Accessories',
    'foreignKey' => 'model_id',
    'targetForeignKey' => 'accessory_id'
]);
$this->belongsToMany('ParentAccessoryModels', [
    'className' => 'Models',
    'through' => 'Accessories',
    'foreignKey' => 'accessory_id',
    'targetForeignKey' => 'model_id'
]);

删除模型时,我想确保它没有被用作另一个模型的附件(子项)。所以我尝试在 ModelsTable 中创建一个自定义规则,但这行不通(它不会删除任何模型,即使它不是另一个模型的附件)。

$rules->addDelete(function ($entity, $options) use($rules) {
    $rule = $rules->existsIn(['accessory_id'], 'ParentAccessoryModels');
    return !$rule($entity, $options);
}, 'isNotAnAccessory');

有什么想法吗?

我通过 beforeDelete 事件解决了这个问题:

public function beforeDelete($event, $entity, $options)
{
    $parentsModels = $this->get($entity->id, ['contain' => 'ParentAccessoryModels']);
    if (!empty($parentsModels->parent_accessory_models)) {
        return false;
    };
}