Your Location is: Home > Php

Delete row from DB asociated with other table with laravel

From: Turkey View: 1497 André Cuellar Avaroma 

Question

I have 4 tables in my DB

mail_tasks => MailTask (class)
mail_messages => MailMessage (class)
meos => Meo (class)
mail_recipients => MailRecipient (class)

I need to delete all rows from 3 first tables in that list containing non-null values for "deleted_at", in other words remove the rows with forceDelete (this rows are previously removed with softdelete)

the problem is that I need to first remove the associations that each have with the different tables

MailTask is associated with Meos table
Meos is associated with MailRecipient

MailTask migration and association

    $table->foreign('meo_id')->references('id')->on('meos')->onDelete('cascade');

MailRecipients migration and association

    $table->foreign('meo_id')->references('id')->on('meos')->onDelete('cascade');

Meos migration and associations

    $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
    $table->foreign('business_type_id')->references('id')->on('business_types')->onDelete('cascade');
  1. I need to delete MailMessages where "deleted_all" is not null
  2. I need to delete MailTask where "deleted_all" is not null and delete first associations with Meo
  3. I need to delete Meo where "deleted_all" is not null and delete first associations with MailRecipients

I have this but I don't understand how can I delete the associations

public function handle()
{
   $mailMessage = MailMessage::query()->whereNotNull('deleted_at');
   $mailMessage->forceDelete();
   $mailTask = MailTask::query()->whereNotNull('deleted_at');
   $mailTask->forceDelete();
   $meo = Meo::query()->whereNotNull('deleted_at');
   $meo->forceDelete();
}

It's okay If I do this? Or I need to do more things?

Best answer