[英]Replacing composite primary key with sequential id in laravel
我有一個帶有復合主鍵的表。 我想創建一個刪除該主鍵的遷移,並引入一個順序的新列“ id”,它將成為新的主鍵。
Schema::table('cart_line', function (Blueprint $table) {
$table->dropPrimary('cart_line_pkey');
$table->increments('id');
$table->primary('id');
});
此代碼引發以下錯誤:
SQLSTATE[42P16]: Invalid table definition: 7 ERROR: multiple primary keys for table "cart_line" are not allowed (SQL: alter table "cart_line" add primary key ("id"))
如果我直接執行以下SQL,則會刪除主鍵,並且上面的代碼將正確執行:
ALTER TABLE cart_line DROP CONSTRAINT cart_line_pkey;
這就是為什么我嘗試
DB::statement('ALTER TABLE cart_line DROP CONSTRAINT cart_line_pkey;');
Schema::table('cart_line', function (Blueprint $table) {
$table->increments('id');
$table->primary('id');
});
但是會引發相同的錯誤。 不會刪除舊的主鍵,但是在嘗試創建新的主鍵之前不會出錯。
我正在使用laravel 5.5和postgres 9.6
刪除$table->primary('id')
因為 $table->increments('id')
使id列為主鍵
Schema::table('cart_line', function (Blueprint $table) {
$table->dropPrimary('cart_line_pkey');
$table->increments('id');
});
您需要在單獨的閉包中執行此操作,因此請嘗試以下操作:
Schema::table('cart_line', function (Blueprint $table) {
$table->dropPrimary('cart_line_pkey');
});
Schema::table('cart_line', function (Blueprint $table) {
$table->increments('id');
});
問題是事務尚未提交,因此使其成為兩個事務就可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.