124697
124697

Reputation: 21893

onDelete('cascade') not deleting data on pivot table

I have the following migration:

 public function up()
    {
        Schema::create('topics_to_subscriptions', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->integer('topic_id')->unsigned();
            $table->integer('subscription_id')->unsigned();

            $table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
        });
    }

My undersatnding is that when using onDelete('cascade'), if I delete a subscription, then all associated TopicsToSubscriptions will be delete.

When I run App\Subscription::truncate(); all the subscriptions are deleted correctly from subscriptions table but no data is deleted from topics_to_subscriptions. what am I doing wrong?

Upvotes: 0

Views: 269

Answers (1)

user1669496
user1669496

Reputation: 33098

You shouldn't be able to truncate a table referenced by foreign keys. I suspect your foreign keys never got applied correctly.

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

public function up()
{
    Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('topic_id')->unsigned();
        $table->integer('youtube_subscription_id')->unsigned();

        $table->foreign('topic_id')->references('id')->on('youtube_topics')->onDelete('cascade');
        $table->foreign('youtube_subscription_id')->references('id')->on('youtube_subscriptions')->onDelete('cascade');
    });
}

Upvotes: 1

Related Questions