微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel迁移已成功迁移,但未在表中创建外键关系

如何解决Laravel迁移已成功迁移,但未在表中创建外键关系

我的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)

但是,当我检查数据库时,没有建立关系,只是建立了外键索引。 Check the Articles Table image in this link. I have marked the necessary parts

Check the Users Table image here. I have highlighted the primary key.

添加了一些与用户和商品有关的工厂数据,当我删除用户时,商品被留为孤儿。

有什么问题吗?

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

先谢谢您。

解决方法

您正在使用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');

});
,

@ShakilAhmmed here

已在评论中回答了该问题。

我要做的只是转到config文件夹,然后转到database.php并将mysql数据库引擎从null更改为innoDB 即 发件人:

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

收件人:

//...
'engine' => 'InnoDB',//...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。