为什么我不能使用约束外键进行迁移

Why I can't do a migration with constraint foreign key

为了家庭作业,我必须在 laravel 7 中做一个 todolist 我做我的数据库,但是当我尝试为 table 任务创建一个外键时

和一个 table 类别 程序失败,公式为:"SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table tasks add constraint tasks_category_id_foreign foreign key (categ ory_id) references categories (id) on delete cascade)"

我已经做了很多次了,但我不明白如果有人能解释我为什么不工作 正确的做法

迁移正在尝试在 categories 之前创建 tasks table,categories table 在它尝试时仍然不存在创建 FK。

交换迁移的顺序以更改其文件名。 database/migrations 中的每个迁移文件在名称前都有一个日期时间。改变它,使任务迁移的日期大于类别之一。

Gus Costa 是对的,你应该按照他说的去做,但我想补充一点 外键应该是 unsigned

在这里你会找到一些很好的答案 "General error: 1005 Can't create table" Using Laravel Schema Build and Foreign Keys

    // CREATING TABLE
    Schema::create('table_name', function (Blueprint $table) {
    $table->engine = 'InnoDB';
        $table->integer('field_id')->unsigned; //for field that contains foreign key constraint
    });

    // FOREIGN KEY CONSTRAINT
    Schema::table('stock', function ($table) {
        $table->foreign('field_id')->references('id')->on('some_table')->onDelete('cascade')->onUpdate('cascade');
    });