errno:150“ laravel迁移中错误地形成了外键约束”错误

问题描述 投票:0回答:1

这是我在运行php artisan migrate后的错误:

SQLSTATE [HY000]:常规错误:1005无法创建表laravelbrands(错误号:150“外键约束格式不正确”)(SQL:更改表brands添加约束brands_b_c_id_foreign外部键(b_c_id)引用countriesc_id))

这是我的模式代码:

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id('c_id');
            $table->string('c_name');
        });
    }
    public function down()
    {
        Schema::dropIfExists('countries');
    }

和:

public function up()
    {
        Schema::create('brands', function (Blueprint $table) {
            $table->id('b_id');
            $table->string('b_name');
            $table->foreignId('b_c_id');
            $table->foreign('b_c_id')->references('c_id')->on('countries');
        });
    }
    public function down()
    {

        Schema::dropIfExists('brands');
    }

[我看到了StackOverflow问题,但对我没有用。我的laravel版本是7.6.0。我的PHP版本是7.4.5。我最近开始学习laravel。有人可以帮我吗?

php mysql database laravel database-migration
1个回答
0
投票

只需更改表的顺序,希望它能解决您的问题

Schema::create('countries', function (Blueprint $table) {
        $table->id('c_id');
        $table->string('c_name');
    });

然后定义或运行

Schema::create('brands', function (Blueprint $table) {
        $table->id('b_id');
        $table->string('b_name');
        $table->foreignId('b_c_id');
        $table->foreign('b_c_id')->references('c_id')->on('countries');
    });
© www.soinside.com 2019 - 2024. All rights reserved.