Home > Software design >  How to update a column as Foreign key on Laravel?
How to update a column as Foreign key on Laravel?

Time:11-09

I'm trying to update a table column as foreign key which references on another table's column.

In example, I have tables named as accounts and currencies. Here are the accounts columns: id, label, currency And Currencies columns: id, label

I have created migrations on both of them like that:

public function up()
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->string('label', 255);
            $table->integer('currency');
        });
    }

Here is the currencies:

public function up()
    {
        Schema::create('currencies', function (Blueprint $table) {
            $table->id();
            $table->string('label', 255);
        });
    }

I want to assign account's currency column to currency's id.

I have tried this:

public function up()
    {
        Schema::table('accounts', function (Blueprint $table) {
            $table->foreign('currency')
                ->references('id')
                ->on('currencies')
                ->onUpdate('cascade');
        });
    }

But it throws this error:

SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`accounts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `accounts` add constraint `accounts_currency_foreign` foreign key (`currency`) references `currencies` (`id`) on update cascade)

How can I write the migration?

CodePudding user response:

the id column in currency is from type: unsignedBigInteger

you have to update currency to this type first to be able to be a foreign key.

public function up()
    {
        Schema::table('accounts', function (Blueprint $table) {
        $table->unsignedBigInteger('currency')->change();
            $table->foreign('currency')
                ->references('id')
                ->on('currencies')
                ->onUpdate('cascade');
        });
    }

or you can modify the first migration if possible.

  • Related