简体   繁体   English

Laravel onDelete级联多对多关系

[英]Laravel onDelete cascade many-to-many relationship

Let's say we have Table A, B and C (with their timestamps accordingly) 假设我们有表A,B和C(相应地带有时间戳)

Table ZZ
id
some_fieldZ

Table YY
id
some_fieldY

Table XX
id
b_id
a_id
some_fieldX

Schema::table('XX', function (Blueprint $table) {
    $table->foreign('ZZ')->references('id')->on('ZZ')->onDelete('cascade');
    $table->foreign('YY')->references('id')->on('YY')->onDelete('cascade');
});

Is it possible to, whenever a record in YY or ZZ is deleted, to XX delete accordingly (and possibly YY/ZZ) without changing its structure (switching one of the FK from one table to another)? 每当删除YY或ZZ中的记录时,是否有可能在不更改其结构的情况下(相应地将FK的一个从一个表切换到另一个表)相应地(可能还有YY / ZZ)删除XX?

Edit: Adding a line to the delete function the other record according to an id or having an Observer is two of the solutions I'm thinking just trying to explore other possible ways to achieve it 编辑:根据ID或在具有Observer的其他记录上向删除功能添加一行,这是我想尝试探索实现它的其他可能方法的两个解决方案

This is one solution without tackling it in schema , but using boot function inside model [that won't change any structure, no migration update needed then]: Make sure you have relationship in your parent model: 这是一种解决方案,无需在schema中进行处理,而是在模型内部使用启动功能[不会更改任何结构,因此不需要迁移更新]:确保父模型中有关联:

public function XXs()
{
    return $this->hasMany(Path\to\XX::class, 'id', 'id');
}

Then insert a trigger in your parent model (I assume : YY and/or ZZ) 然后在您的父模型中插入一个触发器(假设:YY和/或ZZ)

protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model) {
            //Delete XXs first
            $model->XXs()->delete();
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM