【问题标题】:Laravel Migrations are migrating successfully but they are not creating foreign key relationship in tablesLaravel 迁移已成功迁移,但未在表中创建外键关系
【发布时间】:2020-12-16 10:04:31
【问题描述】:

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

提前谢谢你。

【问题讨论】:

  • 您的表是否使用 InnoDB 引擎?
  • 哇!不,那个功能是空的并且已经添加了它然后它就像魔术一样工作。谢谢!
  • @ShakilAhmmed,您介意将其添加为答案以便我标记它吗?以便将来可以帮助其他人?
  • 当然,我已经将它添加为答案。
  • @ShakilAhmmed 不,你还没有,我还是会添加它..

标签: php laravel laravel-migrations laravel-relations


【解决方案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');

});

【讨论】:

    【解决方案2】:

    @ShakilAhmmed here 的评论已经回答了这个问题

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

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

    收件人:

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

    【讨论】:

      猜你喜欢
      • 2023-01-04
      • 2019-05-17
      • 2016-12-07
      • 2013-09-26
      • 2017-07-02
      • 1970-01-01
      • 2020-04-13
      • 2020-05-08
      • 2020-06-05
      相关资源
      最近更新 更多