0

我的 Laravel 应用程序成功创建了迁移中的所有表,但是当我删除主记录时,它无法在表中创建外键关系甚至强制级联。这里是迁移。

    Schema::create('articles', function (Blueprint $table) {
        $table->id('id');
        $table->unsignedBigInteger('user_id');
        $table->string('title');
        $table->text('excerpt');
        $table->text('body');
        $table->timestamps();

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

    });

当我运行 php artisan migrate它迁移成功。

λ php artisan migrate

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.11 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.1 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (0.07 seconds)
Migrating: 2020_08_26_122846_create_articles_table
Migrated:  2020_08_26_122846_create_articles_table (0.14 seconds)

但是,当我检查数据库时,没有创建关系,只是为外键创建索引。 检查此链接中的文章表图像。我已经标记了必要的部分

在此处查看用户表图像。我已经突出显示了主键。

我添加了一些与用户和文章相关的工厂数据,当我删除用户时,文章将被视为孤儿。

有什么问题?

  • PHP版本:7.3.21
  • MySql 版本:5.7.31
  • MariaDB 版本:10.4.13
  • Laravel 框架版本:7.25.0

先感谢您。

4

2 回答 2

1

Schema::create用于创建表格。

在 Laravel 文档中,我看到Schema::table使用外键时。也许您应该尝试拆分代码:

Schema::create('articles', function (Blueprint $table) {
    $table->id('id');
    $table->unsignedBigInteger('user_id');
    $table->string('title');
    $table->text('excerpt');
    $table->text('body');
    $table->timestamps();
});

Schema::table('articles', function (Blueprint $table) {
    $table->foreign('user_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');

});
于 2020-08-27T13:53:48.523 回答
1

@ShakilAhmmed在这里的评论中已经回答了这个问题

我所做的只是去config文件夹然后database.php将mysql数据库引擎从null更改为innoDB,即来自:

//...
'engine' => null,
//...

至:

//...
'engine' => 'InnoDB',
//...
于 2020-08-28T11:15:23.467 回答