簡體   English   中英

將包含外鍵的列添加到 Laravel 中生產中的現有表

[英]Adding column containing foreign key to existing table in production in Laravel

我有一個表格participant ,它與表格campaign many-to-one關系。 現在由於一些愚蠢的原因,我忘記添加一個列campaign_id ,它保存表campaign中行的外鍵。 現在為了解決這個問題,我可以輕松地將以下行添加到create_participants_table遷移文件並運行php artisan migrate:fresh命令,這將刪除所有表並使用正確的列重新創建它們。

$table->unsignedBigInteger('campaign_id');

但問題是兩個表都已經在生產中並且已經包含數據,因此運行migrate:fresh不是最佳選擇。 因此,在這種情況下,我將創建另一個名為add_campaign_id_to_participants遷移文件, add_campaign_id_to_participants所示:

public function up()
{
    Schema::table('participants', function (Blueprint $table) {
        $table->unsignedBigInteger('campaign_id');
    });
}

問題是,當運行php artisan migrate我收到一個錯誤,即Cannot add a NOT NULL column with default value NULL 這看起來很公平,因為該列不可為空並且沒有默認值。 但是使列可以為空或設置默認值似乎並不可取。

現在我的participants表與表visitors one-to-one關系,每個參與者都有一個訪問者,但不是每個訪問者都有一個參與者。 此外, visitors表與表campaign many-to-one關系。 這意味着理論上我可以為參與者填寫剛剛創建的campaign_id ID,例如:

$participant->visitor->campaign->id

現在我的問題是這是否有可能,如果是,我將如何實現這一目標?

我通過將以下內容添加到add_campaign_id_to_participants遷移文件來修復它。

public function up()
{
    Schema::table('participants', function (Blueprint $table) {
        $table->unsignedBigInteger('campaign_id')->default(0);
    });
    $participants = Participant::all();
    foreach($participants as $participant)
    {
        $participant->campaign_id = $participant->visitor->campaign_id;
        $participant->save();
    }
}

暫無
暫無

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

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