2

Let's say we have Table A, B and C (with their timestamps accordingly)

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)?

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

abr
  • 2,071
  • 22
  • 38
  • yes, possible and what you are doing could do the trick – Sohel0415 Jan 19 '18 at 15:26
  • You can indeed either use the `onDelete` on the FK in the table, or create an observer which will handle the deletions. I personally prefer the observer method, because then you're able to use `SoftDeletes` on your eloquent models. – alexr Jan 19 '18 at 15:28
  • thing is, the above example code "doesn't work" if I delete a record in YY table, it won't erase in XX and I want it to – abr Jan 19 '18 at 15:40
  • That's because you'll have to set the `onDelete` on the foreign keys on the other tables as well for it to work. – alexr Jan 19 '18 at 15:49

1 Answers1

3

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:

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)

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

        static::deleting(function ($model) {
            //Delete XXs first
            $model->XXs()->delete();
        });
    }
4givN
  • 2,936
  • 2
  • 22
  • 51
  • here is also some good explanation for this scenario: https://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm – edgar mlowe Apr 22 '20 at 03:48