laravel cascade not working?

- 1 answer

Ad

I'm building a ticketsystem with laravel. But when I remove a ticket the reactions don't go away?

This is my migration of the pivot table:

public function up()
    {
        Schema::create('reactions_ticket',function(Blueprint $table)
            {
                $table->integer('ticket_id')->unsigned();
                $table->foreign('ticket_id')->references('id')->on('ticket')->onDelete('cascade');
                $table->integer('reactions_id')->unsigned();
                $table->foreign('reactions_id')->references('id')->on('reactions')->onDelete('cascade');
            });
    }

And this is my reaction table:

 public function up()
    {
        Schema::create('reactions',function(Blueprint $table)
            {
                $table->increments('id');
                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->text('content');
                $table->timestamps();
            });
    }

and my ticket table:

   public function up()
        {
            Schema::create('ticket',function(Blueprint $table)
            {
                $table->increments('id');
                $table->string('slug')->nullable();

                $table->integer('ticketid')->unsigned();

                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

                $table->integer('subject_id')->unsigned();
                $table->foreign('subject_id')->references('id')->on('subject')->onDelete('cascade');

                $table->integer('websites_id')->unsigned();
                $table->foreign('websites_id')->references('id')->on('websites')->onDelete('cascade');

                $table->integer('status_id')->unsigned();
                $table->foreign('status_id')->references('id')->on('status')->onDelete('cascade');

                $table->text('content');
                $table->timestamps();
            });
        }

What am I doing wrong>?

Ad

Answer

Ad

I would always prefer to handle such actions by myself instead of let id be done by MySQL.

You could use laravels event-handler inside your Ticket model.

protected static function boot() {
    parent::boot();
    static::deleting(function($ticket) {
        // delete related stuff ;)
        $reaction_ids = $ticket->reactions()->lists('id');
        Reaction::whereIn($reaction_ids)->delete();
    });
}

So you still have (if you want/need) the advantage of softdelete and more controll.

Ad
source: stackoverflow.com
Ad