簡體   English   中英

如何在 Laravel 上將列更新為外鍵?

[英]How to update a column as Foreign key on Laravel?

我正在嘗試將表列更新為引用另一個表列的外鍵。

例如,我有名為帳戶和貨幣的表。 以下是賬戶列:id、label、currency 和 Currencies 列:id、label

我已經像這樣在他們兩個上創建了遷移:

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

這是貨幣:

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

我想將accountcurrency列分配給currencyid

我試過這個:

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

但它拋出這個錯誤:

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)

我該如何編寫遷移?

貨幣中的 id 列來自類型: unsignedBigInteger

您必須首先將貨幣更新為這種類型才能成為外鍵。

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

或者如果可能,您可以修改第一次遷移。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM