【问题标题】:(errno: 150 "Foreign key constraint is incorrectly formed")(errno: 150 "外键约束格式不正确")
【发布时间】:2018-03-02 11:33:26
【问题描述】:

我是 Laravel 的新手。我之前创建了users 表。 employment 表已在迁移中创建。作为下一次迁移,我更改了users 表以将employment 表中的job_id 添加到users 表中。当我运行迁移时,它给出了上述错误。

注意:我需要将employment 表中的job_idjob_id 的形式提供给users 表。 soumya 是我的数据库名称

当我在没有外键约束的情况下运行迁移时,它可以完美运行。

迁移:就业表

    public function up()
{
    Schema::create('employment', function (Blueprint $table) {
        $table->increments('job_id');
        $table->string('job_title');
        $table->string('job_description')->nullable()->default(NULL);
        $table->string('slug')->unique();


        $table->timestamps();
    });
}
    public function down()
{
    Schema::drop('employment');
}

迁移更改 users

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->integer('job_id')->after('deleted');
        $table->foreign('job_id')->references('job_id')->on('employment');
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropForeign('users_job_id_foreign');
        $table->dropColumn('job_id');

    });
}

【问题讨论】:

  • 该错误纯粹与mysql有关,与php或laravel无关,stackoverflow.com/…,一旦您在mysql中得到错误原因,在php端进行编辑将是小菜一碟。
  • 尝试把这个$table->integer('job_id')->after('deleted');改成这个$table->unsignedInteger('job_id')->after('deleted');
  • @Maraboc 它给出了完整性错误。
  • 试试这个$table->integer('job_id')->unsigned(); !!

标签: php mysql laravel foreign-keys migration


【解决方案1】:

像这样更改您的用户迁移

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->unsignedInteger('job_id');
        $table->foreign('job_id')->references('job_id')->on('employment');
    });
}

【讨论】:

  • 我添加了截图。 “soumya”是我的数据库名称
【解决方案2】:

在 laravel 中,表格是按照先到先得的方式迁移的。确保外键引用的表在包含外键的表之前迁移。

为此,您可以更改迁移文件的名称,以便用户表的迁移在项目目录中的就业表迁移之前存在。

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2020-07-07
    • 1970-01-01
    • 2017-04-13
    • 2018-09-04
    • 2019-09-17
    • 2020-12-16
    • 2019-09-15
    相关资源
    最近更新 更多