0

i have 4 models which are related with each other.. 1st Model: school:

 
     public function contactpersons()
    {
        return $this->hasMany(ContactPerson::class, 'school_id', 'id');
    }

2nd Model: ContactPerson:

  public function addresses()
    {
        return $this->belongsToMany(Address::class, 'address_contact_person', 'contact_person_id', 'address_id');
    }

3rd Model: Address:

 public function contactPersonAddresses()
    {
        return $this->belongsToMany(ContactPerson::class, 'address_contact_person', 'address_id', 'contact_person_id');
    }

4th model: pivot table

AddressContactPerson:

Now the question is .. i want my records of Address and AddressContactPerson to be deleted when i delete the contact person . i tried with firing delete events but couldnt make it. the events were not triggerd .. i have to delete these records from School Model.. $school->contactpersons()->delete(); and i have softDeletes on every Models. this will only delete contactpersons record not the 'Address' and AddressContactPerson table..

Ravi Sigdel
  • 161
  • 10
  • Does this answer your question? [Automatically deleting related rows in Laravel (Eloquent ORM)](https://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm) – Felippe Duarte Sep 03 '20 at 14:57
  • no it didnt .. i did look at it but it didnt help me .. when i delete the school it deletes the contactperson but wont further delete the address and addresscontactperson table... thats what i am looking for .. couldnt find a way . – Ravi Sigdel Sep 03 '20 at 15:03
  • Can you show more of your code. In which model you have made what relationships? – dqureshiumar Sep 03 '20 at 15:22

1 Answers1

0

In your Schema you should have a foreign key and then set onDelete('cascade'). Something like this:

$table->biginteger('user_id')->unsigned()->index();
$table->foreign('user_id')
      ->references('id')
      ->on('users')
      ->onDelete('cascade');
dqureshiumar
  • 810
  • 1
  • 7
  • 19
Daitarn
  • 109
  • 1
  • 15
  • how am i supposed to assign foreign key on contactperson model when it doesnt have any id related with address table ? – Ravi Sigdel Sep 03 '20 at 15:04
  • In your model you should have a delete() function in which you call the delete() function on your relationship. E.g if you have a user model and when you delete a user you want to delete all the relationship associated, you should try something like that:`public function delete() { DB::transaction(function() { $this->yourRelationship()->delete(); parent::delete(); });` – Daitarn Sep 03 '20 at 15:47