[英]Laravel :: Best way to update a foreign key
我有這個遷移文件
Schema::create('table_one', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('table_two_id')->unsigned();
$table->foreign('table_two_id')->references('id')->on('table_two');
$table->timestamps();
});
我想更新以使其->onDelete('cascade');
$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');
做這個的最好方式是什么?
有沒有類似->change();
謝謝
刪除外鍵,然后再次添加並運行遷移。
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->dropForeign(['table_two_id']);
$table->foreign('table_two_id')
->references('id')
->on('table_two')
->onDelete('cascade');
});
}
Christopher K. 是對的,在 Laravel 文檔中說:
要刪除外鍵,您可以使用 dropForeign 方法。 外鍵約束使用與索引相同的命名約定。 因此,我們將連接表名和約束中的列,然后在名稱后綴 "_foreign" :
$table->dropForeign('posts_user_id_foreign');
或者,您可以傳遞一個數組值,該值將在刪除時自動使用常規約束名稱:
$table->dropForeign(['user_id']);
https://laravel.com/docs/5.7/migrations#foreign-key-constraints
composer require doctrine/dbal
Schema::table('table_one', function (Blueprint $table) {
$table->foreignId('table_two_id')
->change()
->constrained('table_two')
->onDelete('cascade');
});
php artisan migrate
你需要刪除
public function up()
{
Schema::table('<tableName>', function (Blueprint $table) {
$table->dropForeign('<FK-name>');
$table->dropColumn('<FK-columnName>');
});
Schema::table('<tableName>', function (Blueprint $table) {
$table->foreignId('<FK-columnName>')->constrained()->cascadeOnDelete();
});
}
有兩個查詢。 在 Laravel 8 上工作
1- 設置粗加工:
Route::get('foreignkeyforimg', "foreignkey@index"); 2- 使用外鍵名稱創建控制器。
3- 具有從遷移類擴展的外鍵控制器。
4-轉到數據庫並從表中手動刪除舊的主鍵
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class Foreignkey extends Migration
{
function index(){
Schema::table('images', function (Blueprint $table) {
$table->foreign('sub_cat_id')
->references('id')
->on('subcategories')
->onDelete('cascade');
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.