3
votes

I have a table with an already created foreign key constraint:

$table->foreign('cms_id')->references('id')->on('inventories');

I need to change this foreign key so that it references remote_id and not id column in the inventories table.

I have tried that by doing this:

    public function up()
    {
        Schema::table('contents', function (Blueprint $table) {
            $table->dropForeign('contents_cms_id_foreign');
            $table->foreign('cms_id')->references('remote_id')->on('inventories');
        });
    }

But, I get:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table contents add constraint contents_cms_id_foreign foreign k ey (cms_id) references inventories (remote_id))

[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

1
Make sure that cms_id and remote_id are of the same type, size and have the same properties (like e.g. UNSIGNED etc.).lesssugar
They are of the same type, and have same properties, but I still get the same errorLeff

1 Answers

6
votes

Add new foreign key in two steps, aside from separating to Schema::table:

public function up()
{
    Schema::table('contents', function (Blueprint $table) {
        $table->dropForeign('contents_cms_id_foreign');
        $table->integer('cmd_id')->unsigned();
    });

    Schema::table('contents', function (Blueprint $table) {
        $table->foreign('cms_id')->references('remote_id')->on('inventories');
    });
}