(错误:150“外键约束形成错误”)

时间:2017-09-21 07:56:24

标签: php mysql laravel foreign-keys migration

enter image description here我是Laravel的新手。我之前创建了users表。 employment表已在迁移中创建。在下一次迁移时,我更改了users表以在job_id表中添加employmentusers表。当我运行迁移时,会出现上述错误。

注意:我需要将job_id表中的employment作为users提供给job_id表。 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');

    });
}

2 个答案:

答案 0 :(得分:0)

像这样更改您的用户迁移

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

答案 1 :(得分:0)

在laravel中,表格按先到先得的原则进行迁移。确保在包含外键的表之前迁移外键引用的表。

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

相关问题