2017-09-14 69 views
0

我可以創建指向唯一組合鍵的外鍵嗎?在laravel中使用unique(),mysql是否正確運行onDelete Cascade?

 $table->integer('project_id')->unsigned(); 
     $table->unsignedBigInteger('unique_id'); 
     $table->bigInteger('parent_id')->unsigned()->nullable(); 


     $table->unique(['unique_id', 'project_id'], 'parent_unique_id')->unsigned(); 

,然後做到這一點:

$table->foreign('parent_id')->references('parent_unique_id')->on('todos')->onDelete('cascade'); 

我認爲這是可行的,但是當我嘗試這個失敗。

mysql允許外鍵指向唯一的複合字段嗎?或者我應該這樣做:

$table->index(['unique_id', 'project_id'], 'parent_index'); 

$table->foreign('parent_id')->references('parent_index')->on('todos')->onDelete('cascade'); 

外鍵的原因是,刪除父指向它的所有行也被刪除。

問題的只是在做:

$table->foreign('parent_id')->references('parent_id')->on('todos')->onDelete('cascade'); 

是PARENT_ID可能不是每個項目唯一的,所以這意味着刪除父和所有行也將被刪除,即使它們屬於另一個項目。

回答

1

試試這個 -

$table->integer('parent_id')->nullable()->unsigned()->index(); 
$table->foreign('parent_id')->references('parent_id')->on('todos')->onDelete('cascade'); 

這是一個另類 -

$table->foreign('parent_id')->references('parent_id')->on('todos')->onDelete('restrict')->onUpdate('no action'); 

希望這會爲你工作。

相關問題