簡體   English   中英

當外鍵也是 Laravel 遷移的自表主鍵時,更改列以執行 onDelete('restrict')

[英]Alter a column to perform onDelete('restrict') when foreign key is also primary key of self table for Laravel migrations

我有兩個表 (**tbl_Traditional_Policysummery_KYC **& tbl_UnderwritingWorkSheetInfo ) 兩個表的主鍵都是PolicyNo

我想限制表**tbl_Traditional_Policysummery_KYC的刪除操作**當tbl_UnderwritingWorkSheetInfo具有相同PolicyNO的值時

我已經嘗試過這些遷移

$table->string('PolicyNo')->unsigned()->index()->change();
            $table->foreign('PolicyNo')
                ->references('PolicyNo')->on(with(new WorksheetInfo)->getTable())
                ->onDelete('restrict');

<?php

use App\Models\PolicySummaryKYC;
use App\Models\WorksheetInfo;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddForeignKeyConstaintToKYCTable extends Migration
> {
>     /**
Run the migrations.
*
* @return void
*/
public function up()
>     {
Schema::table(with(new PolicySummaryKYC)->getTable(), function (Blueprint $table) {
>             $table->string('PolicyNo')->unsigned()->index()->change();
>             $table->foreign('PolicyNo')
>                 ->references('PolicyNo')->on(with(new WorksheetInfo)->getTable())
>                 ->onDelete('restrict');
>         });
>     }

>     /**
Reverse the migrations.
*
* @return void
*/
public function down()
>     {
Schema::table(with(new PolicySummaryKYC)->getTable(), function (Blueprint $table) {
>             //
>         });
>     }
> }

這是您需要在遷移中設置的內容 up()

Schema::table('tbl_Traditional_Policysummery_KYC', function (Blueprint $table) {
  $table->foreign('PolicyNo')
     ->references('PolicyNo')
     ->on('tbl_UnderwritingWorkSheetInfo')
     ->onDelete('restrict');
});

筆記:

  • 我假設您之前已經創建了另一個遷移到tbl_Traditional_Policysummery_KYC ,您在其中將PolicyNo聲明為字符串和主鍵( $table->string('PolicyNo')->primary();
  • 無需將unsigned()添加到字段類型string() ,它僅適用於 integer,您的 PolicyNo 字段是字符串
  • 因為 PolicyNo 字段已經是primary,不需要索引
  • 要獲取表名,可以使用(new App\Models\ModelName)->getTable() ,無需在 Model class 之外使用with(...)

暫無
暫無

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

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