![](/img/trans.png)
[英]Alter primary key column that is also a foreign key of another table - Mysql
[英]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 字段是字符串(new App\Models\ModelName)->getTable()
,無需在 Model class 之外使用with(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.