2017-09-21 107 views
0

enter image description here我是Laravel的新手。我以前创建了users表。 employment表已在迁移中创建。作为下一次迁移我已经改变users表添加job_idemployment表到users表。当我运行迁移时,会出现上述错误。(错误:150“外键约束不正确”)

注意:我需要在employment表中给job_idusers表作为job_idsoumya是我的数据库名称

当我运行没有外键约束的迁移时,它可以很好地工作。

Migations:就业表

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'); 

    }); 
} 
+0

该错误纯粹与mysql有关,不是php也不是laravel,一旦你在mysql中得到了错误原因在PHP方面编辑将是一个和平的蛋糕。 – hassan

+0

[迁移:无法在laravel中添加外键约束]可能的重复(https://stackoverflow.com/questions/22615926/migration-cannot-add-foreign-key-constraint-in-laravel) – hassan

+0

尝试更改此' ('deleted');'到'this'$ table-> unsignedInteger('job_id') - > after('deleted');' – Maraboc

回答

0

改变这样

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

给出错误完整性违规 – Shyamali

+0

mmm你能告诉我完整的错误吗? –

+0

我添加了屏幕截图。 “soumya”是我的数据库名称 – Shyamali

0

在laravel您的用户迁移,表上的第一先到迁移先到先得。确保外键所引用的表在包含外键的表之前被迁移。

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