0

I have two models: model 1 field id, field_a, field_b

model 2 id2, field_a, field_b

on $model1->delete() I would like to delete also $model2 where field_a and field_b are the same of $model1 (both of them)

Example

model1
1, 2, 5

model2
1, 2, 4
2, 3, 5
3, 2, 5 (to be deleted)

I don't know if this could be helpful Automatically deleting related rows in Laravel (Eloquent ORM)

Community
  • 1
  • 1
lorenzo
  • 187
  • 2
  • 8

2 Answers2

1

Register a delete event on model 1 that deletes model 2 where the values match.

In model 1 add the following...

public static function boot()
{
    parent::boot();
    static::deleted(function($model1) {
        Model2::where('field_1', $model1->field_1)->where('field_2', $model1->field_2)->delete()
    });
}

Now whenever you delete model 1, model 2 with matching attributes are also removed.

user1669496
  • 32,176
  • 9
  • 73
  • 65
0

Just find and delete the rows from model2 where the column values are similar.

Model2::where('field_a',$model1->field_a)->where('field_b',$model1->field_b)->delete();

$model1->delete();

Here, Model2 is the class of the Second model.

Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34