简体   繁体   中英

Deleting related records in Laravel 5.1 (Eloquent ORM)

I have customers model, which hasMany Locations , and Locations hasMany contacts .

I want to delete the Customer and all its locations and contacts.

Now below code removes the locations successfully :

$customer = Customer::find($id);
$customer->locations()->delete();

But I want to remove the Contacts as well.

Ideally I want the code like :

$customer->locations()->contacts()->delete();

Is it possible??

You could set this up in your migrations by specifying the onDelete('cascade') in your pivot table, take a look at foreign-key-constraints , eg :

$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');

Or use eloquent events , what you want in this case is the "deleting" event to do the cleanup.

Customer Model :

class Customer extends Eloquent
{
    protected static function boot() {
        parent::boot();

        static::deleting(function($customer) { 
             $customer->locations()->delete();
        });
    }
}

Location Model :

class Location extends Eloquent
{
    protected static function boot() {
        parent::boot();

        static::deleting(function($location) {
             $location->contacts()->delete();
        });
    }
}

Hopet this helps.

You Could define this in your Models.

Customer Model

class Customer extends Eloquent
{
    public function locations()
    {
        return $this->has_many('Location');
    }

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

        static::deleting(function($customer) { 
             // before delete() method call this
             $customer->locations()->delete();
             // do the locations cleanup...
        });
    }
}

And in your Locations Model

class Location extends Eloquent
    {
        public function contacts()
        {
            return $this->has_many('Contact');
        }

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

            static::deleting(function($location) { 
                 // before delete() method call this
                 $location->contacts()->delete();
                 // do the contacts cleanup...
            });
        }
    }

And Now

$customer = Customer::find($id);
$customer->delete();

Should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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