0

I have a example of cascade delete but it looks too big and complicated, is there a way to shorten this code?

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

        static::deleted(function ($parent) {
            // $versions = $parent->game_versions();
            $versions = $parent->game_versions;
            foreach($versions as $version){
                $version->delete();
            }
        });
    }

Someone can help me with that?

3 Answers3

0

Hello you can use CASCADE DELETE, you can modify the foreign key constraint in your migration that creates the game_versions table to include the onDelete method with a value of "cascade", like so:

Schema::create('game_versions', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('game_id');
    $table->foreign('game_id')->references('id')->on('games')->onDelete('cascade');
    $table->string('version_number');
    $table->timestamps();
});

This will ensure that when a Game record is deleted, all related GameVersion records with the corresponding game_id will also be deleted from the database.

Timur Rodya
  • 157
  • 1
  • 1
  • 6
-1

you can simplify the foreach as this.

foreach($versions as $version as $v)->delete()
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Ashan
  • 1
-1

For example, the following code will erase all game versions when a game is deleted:

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

    static::deleted(function ($parent) {
        $parent->game_versions()->delete();
    });
}