Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1915
半阙折子戏
半阙折子戏 2020-11-22 17:03

When I delete a row using this syntax:

$user->delete();

Is there a way to attach a callback of sorts, so that it would e.g. do this auto

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 17:56

    I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the "deleting" event to do the cleanup:

    class User extends Eloquent
    {
        public function photos()
        {
            return $this->has_many('Photo');
        }
    
        // this is a recommended way to declare event handlers
        public static function boot() {
            parent::boot();
    
            static::deleting(function($user) { // before delete() method call this
                 $user->photos()->delete();
                 // do the rest of the cleanup...
            });
        }
    }
    

    You should probably also put the whole thing inside a transaction, to ensure the referential integrity..

提交回复
热议问题