Laravel 5: cascade soft delete

后端 未结 4 1598
醉话见心
醉话见心 2020-12-24 07:54

I am having offers and services table.

Service(s) is a child of an offer. So far I have established functionality for soft deletin

相关标签:
4条回答
  • 2020-12-24 08:24

    I have put this code in Offer model:

    protected static function boot() {
        parent::boot();
    
        static::deleting(function($offer) {
            $offer->services()->delete();
        });
    }
    

    And added missing

    use SoftDeletes;
    protected $dates = ['deleted_at'];
    

    in the Service model.

    0 讨论(0)
  • 2020-12-24 08:42

    You should use Eloquent events for this.

    Offers::deleted(function($offer) {
        $offer->services()->delete();
    });
    
    Offers::restored(function($offer) {
        $offer->services()->withTrashed()->restore();
    });
    
    0 讨论(0)
  • 2020-12-24 08:44

    You can do like this.

    self::deleting(function($offer) {
        $offer->services()->delete();
    });
    
    self::restoring(function ($offer) {
       $offer->services()->restore();
    });
    

    You should first delete/restore the children records (services) before deleting/restoring the parent (offer). Failing to do this, will trigger referential integrity MySql error.

    0 讨论(0)
  • 2020-12-24 08:50

    If you want to get cascading softDeletes in your Eloquent Models I highly recommend using this library iatstuti/laravel-cascade-soft-deletes

    Composer

    // get it with composer.
    $ composer require iatstuti/laravel-cascade-soft-deletes="1.0.*"
    

    Quick example

    The one provided in the getting started sample.

    <?php
    
    namespace App;
    
    use App\Comment;
    use Iatstuti\Database\Support\CascadeSoftDeletes;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Post extends Model
    {
        use SoftDeletes, CascadeSoftDeletes;
    
        protected $cascadeDeletes = ['comments'];
    
        protected $dates = ['deleted_at'];
    
        public function comments()
        {
            return $this->hasMany(Comment::class);
        }
    }  
    
    0 讨论(0)
提交回复
热议问题