首页 > 解决方案 > 在 Laravel 8 中获取“错误地通知外键约束”

问题描述

我正在尝试使用 foreignId 从另一个表中获取 ID,但它不会让我这样做。

我的用户表:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('user_id');
            $table->string('first_name', 40);
            $table->string('last_name', 40);
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->foreignId('tier_id')->references('tier_id')->on('tiers');
            $table->rememberToken();
            $table->timestamps();
        });
    }

我的等级表:

public function up()
    {
        Schema::create('tiers', function (Blueprint $table) {
            $table->id('tier_id');
            $table->string('name');
            $table->float('price');
            $table->string('max_resolution');
            $table->integer('max_users');
            $table->timestamps();
        });
    }

我做错了什么,请帮忙!

解决了,方法如下:Espresso 的评论似乎有帮助,迁移完美完成,我需要做的就是更改文件名。谢谢!

标签: phpsqllaravel

解决方案


你能像那个父表一样尝试你的迁移吗?

public function up()
    {
        Schema::create('tiers', function (Blueprint $table) {
            $table->increments('tier_id');
            $table->string('name');
            $table->float('price');
            $table->string('max_resolution');
            $table->integer('max_users');
            $table->timestamps();
        });
    }

子表

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('users_id');
            $table->string('first_name', 40);
            $table->string('last_name', 40);
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->integer('tier_id')->unsigned()->nullable();
            $table->rememberToken();
            $table->timestamps();

            
            $table->foreign('tier_id')->references('tier_id')->on('tiers');
        });
    }

推荐阅读