Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel changing foreign key constraint

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

like image 405
Leff Avatar asked Nov 20 '25 05:11

Leff


1 Answers

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');
    });
}
like image 73
Cong Chen Avatar answered Nov 22 '25 17:11

Cong Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!