首页 > 解决方案 > Laravel 迁移外键不起作用

问题描述

我正在laravel上创建一个新的应用程序,我正在编写迁移,我想为我的列设置外键,所以我这样做如下:

   Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->integer('type_id');
            $table->string('name');
            $table->integer('status_id')->default(0);
            $table->integer('category_id')->default(0);
            $table->integer('store_id');
            $table->timestamps();
            $table->foreign('status_id')->references('id')->on('product_statuses');
            $table->index('status_id');
            $table->foreign('type_id')->references('id')->on('product_types');
            $table->index('type_id');
            $table->foreign('category_id')->references('id')->on('product_categories');
            $table->index('category_id');
            $table->foreign('store_id')->references('id')->on('stores');
            $table->index('store_id');

但是这些不起作用,因为我在其中检查phpmyadmin它让我插入任何数字而不是来自status_id例如的项目,当我在design选项卡中检查它时,我看不到表之间的关系。#编辑

添加product_types迁移:

 /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_types', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

关于我使用 wamp 和 mysql v8 的引擎,我认为它支持 fk 功能

标签: mysqllaravelmigration

解决方案


正如你在评论中所说:

我看到的是,在表格上的 phpmyadmin 中有一个列在写 :Type :MyISAM 。引擎的意思是一样的吗?

您的数据库默认引擎是不支持关系功能的 MyISAM。

要解决此问题,您可以编辑config/database.php文件,搜索mysql条目并更改:

'engine' => null,

'engine' => 'InnoDB',

然后你必须重新创建表。


如果出于任何原因无法删除并重新创建表,则可以创建新迁移以更改现有表。IE:

public function up()
{
    $tables = [
        'product_types',
        'products',
    ];
    foreach ($tables as $table) {
        DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
    }
}

另一件事,外键列的数据类型必须匹配相关列的相同数据类型。

由于$table->id()$table->bigIncrements('id')laravel 最新版本文档中所述的别名,因此您应该使用:

$table->unsignedBigInteger('type_id');

$table->foreign('type_id')->references('id')->on('product_types');

还要注意顺序:首先创建列,然后是 fk 引用(而不是相反)。

参考:https ://laravel.com/docs/8.x/migrations#foreign-key-constraints


推荐阅读