Laravel 迁移的外键不起作用

Laravel foreign key on migration is not working

我正在 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 功能

在 Laravel 中创建新的 table 时。迁移将生成如下: 你的 table 应该是: $table->增量('id');

而不是(在旧 Laravel 版本中):

$table->id();

正如您在评论中所说:

what i see is that in phpmyadmin on tables there is a column which is writing :Type :MyISAM . is that the same meaning of engine ?

您的数据库默认引擎是 MyISAM,不支持关系特性。

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

'engine' => null,

'engine' => 'InnoDB',

然后您必须重新创建表。


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

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