首页 > 解决方案 > 我如何让我的 cascadeOnDelete 在 laravel 中工作

问题描述

试图学习 Laravel,我正在从头开始学习 laracast 的一个名为 Laravel 8 的教程,现在已经达到了关于级联的情节 https://laracasts.com/series/laravel-8-from-scratch/episodes/53

我没有收到任何错误,但是如果我在帖子中添加评论,然后删除帖子,那么我的评论会保留在数据库中,而他的评论会随帖子一起删除。我尝试使用 laravel 删除帖子,但也使用 tableplus。我的设置与他的有点不同,所以我想知道我的级联是否因为我的设置中的某些东西而无法工作。

评论迁移

Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->cascadeOnDelete();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->text('body');
        $table->timestamps();
    });

迁移后

Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->foreignId('category_id');
        $table->string('slug')->unique();
        $table->string('title');
        $table->text('excerpt');
        $table->text('body');
        $table->timestamps();
        $table->timestamp('published_at')->nullable();
    });

我也试过使用$table->foreignKey('post_id')->references('id')->on('posts')->onDelete('cascade),但我似乎无法让它工作。

我还尝试使用在 mySql 数据库中添加自我约束

alter table
   `comments`
add
   constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on 
delete cascade

我需要特定用途,还是我的设置? 来自 wamp 的 php/数据库设置版本

标签: laravellaravel-8php-7.4

解决方案


我想如果你搜索 myisam 和 innodb,你可能会找到答案。在 myisam 中,不会删除外键


推荐阅读