it-source

외부 키 Larabel 오류가 있는 열 삭제: 일반 오류: 1025 이름 변경 시 오류

criticalcode 2023. 1. 3. 21:46
반응형

외부 키 Larabel 오류가 있는 열 삭제: 일반 오류: 1025 이름 변경 시 오류

이행을 사용하여 다음과 같은 테이블을 만들었습니다.

public function up()
{
    Schema::create('despatch_discrepancies',  function($table) {
        $table->increments('id')->unsigned();
        $table->integer('pick_id')->unsigned();
        $table->foreign('pick_id')->references('id')->on('picks');
        $table->integer('pick_detail_id')->unsigned();
        $table->foreign('pick_detail_id')->references('id')->on('pick_details');
        $table->integer('original_qty')->unsigned();
        $table->integer('shipped_qty')->unsigned();
    });
}

public function down()
{
    Schema::drop('despatch_discrepancies');
}

이 표를 변경하여 외부 키 참조 & 열을 삭제해야 합니다.pick_detail_id라고 하는 새로운 varchar 컬럼을 추가합니다.sku끝나고pick_id기둥.

또 다른 이행을 작성했습니다.이 이행은 다음과 같습니다.

public function up()
{
    Schema::table('despatch_discrepancies', function($table)
    {
        $table->dropForeign('pick_detail_id');
        $table->dropColumn('pick_detail_id');
        $table->string('sku', 20)->after('pick_id');
    });
}

public function down()
{
    Schema::table('despatch_discrepancies', function($table)
    {
        $table->integer('pick_detail_id')->unsigned();
        $table->foreign('pick_detail_id')->references('id')->on('pick_details');
        $table->dropColumn('sku');
    });
}

이 마이그레이션을 실행하면 다음 오류가 나타납니다.

[그림\데이터베이스\]Query Exception ]
SQLSTATE[HY000]: 일반 오류: '.dev_iwms_reboot/despatch_discrepancies'에서 '.dev_iwms_reboot/#sql2-67c-17c464'로 이름 변경 시 1025 오류 발생(SQL: alter table)despatch_discrepancies외부 키 pick_drop_id)

[PDOException]
SQLSTATE[HY000]: 일반 오류: '.dev_iwms_reboot/despatch_discrepancies'에서 '.dev_iwms_reboot/#sql2-67c-17c464'로 이름 변경 시 1025 오류 발생(errno: 152)

실행함으로써 이 이행을 되돌리려고 하면php artisan migrate:rollback명령어, 명령어느 쪽이든Rolled back하지만 실제로는 데이터베이스에서 아무 것도 하지 않습니다.

뭐가 잘못됐는지 알아?외부 키 참조가 있는 열은 어떻게 드롭합니까?

다음을 사용할 수 있습니다.

Schema::table('despatch_discrepancies', function (Blueprint $table) {
    $table->dropForeign(['pick_detail_id']);
    $table->dropColumn('pick_detail_id');
});

dropForeign 소스에서 피크를 사용하는 경우 열 이름을 배열로 전달하면 외부 키 인덱스 이름이 생성됩니다.

다음과 같은 외부 키를 작성하면 다음과 같이 됩니다.

$table->integer('pick_detail_id')->unsigned();
$table->foreign('pick_detail_id')->references('id')->on('pick_details');

Laravel은 외부 키 참조에 다음과 같이 고유하게 이름을 붙입니다.

<table_name>_<foreign_table_name>_<column_name>_foreign
despatch_discrepancies_pick_detail_id_foreign (in my case)

따라서 외부 키 참조가 있는 열을 드롭하려면 다음과 같이 해야 합니다.

$table->dropForeign('despatch_discrepancies_pick_detail_id_foreign');
$table->dropColumn('pick_detail_id');

업데이트:

Larabel 4.2+에서는 새로운 명명 규칙이 도입되었습니다.

<table_name>_<column_name>_foreign

업데이트:

Larave > 8.x는 새로운 기능을 도입했습니다.

dropConstrainedForeignId('pick_detail_id');

그러면 열과 열의 외부 키가 삭제됩니다.

테이블에 여러 개의 외부 키가 있어 다운 방식으로 배열의 인덱스로 열 이름을 전달하여 하나씩 외부 키 제약을 제거해야 했습니다.

public function up()
{
    Schema::table('offices', function (Blueprint $table) {
        $table->unsignedInteger('country_id')->nullable();
        $table->foreign('country_id')
            ->references('id')
            ->on('countries')
            ->onDelete('cascade');

        $table->unsignedInteger('stateprovince_id')->nullable();
        $table->foreign('stateprovince_id')
            ->references('id')
            ->on('stateprovince')
            ->onDelete('cascade');
        $table->unsignedInteger('city_id')->nullable();
        $table->foreign('city_id')
            ->references('id')
            ->on('cities')
            ->onDelete('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('offices', function (Blueprint $table) {
        $table->dropForeign(['country_id']);
        $table->dropForeign(['stateprovince_id']);
        $table->dropForeign(['city_id']);
        $table->dropColumn(['country_id','stateprovince_id','city_id']);
    });
} 

아래 문장을 사용해도 작동하지 않습니다.

$table->dropForeign(['country_id','stateprovince_id','city_id']); 

dropForeign은 삭제할 컬럼을 분리하지 않기 때문입니다.그래서 하나씩 떨어뜨려야 해요.

이 문제를 해결하기 위한 열쇠는 $table->dropForeign() 명령어가 반드시 열 이름이 아닌 올바른 관계 이름을 전달받고 있는지 확인하는 것이었습니다.훨씬 직관적인 IMHO가 되므로 열 이름을 전달하고 싶지 않습니다.

나에게 효과가 있었던 것은, 다음과 같습니다.

$table->dropForeign('local_table_foreign_id_foreign');
$table->column('foreign_id');

따라서 dropForeign()에게 전달한 문자열은 다음과 같은 형식입니다.

[로컬 테이블]_[외부필드]_외부

Sequel Pro나 Navicat과 같은 툴에 접근할 수 있다면, 그것들을 시각화할 수 있다면 매우 도움이 될 것입니다.

건 '는 이었다.Schema::table

나중에 나는 키가 SQL 오류에 있다는 것을 알았다.

[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists `lu_benefits_categories`)

그...Schema::table.down()의 function의 lu_benefits_categories 및 전Schema::dropIfExists 표시:

public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropForeign('table_category_id_foreign');
        $table->dropColumn('category_id');
    });
    Schema::dropIfExists('lu_benefits_categories');
}

후, ,,는php artisan migrate:refresh ★★★★★★★★★★★★★★★★★」php artisan migrate:reset효과가 있을 거야

laravel 8에서는 drop Constrainted ForeignId(https://github.com/laravel/framework/pull/34806)를 사용합니다.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddAddressFieldsInEventTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        
        Schema::table('events', function (Blueprint $table) {
            $table->bigInteger('address_id')->nullable();

            $table->foreign('address_id')
                ->references('id')
                ->on('addresses')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('events', function (Blueprint $table) {
            $table->dropConstrainedForeignId('address_id');
            $table->dropColumn('address_id');
        });
    }
}

먼저 관계 ID를 비활성화할 수 있습니다.

Schema::disableForeignKeyConstraints();

언급URL : https://stackoverflow.com/questions/27175808/dropping-column-with-foreign-key-laravel-error-general-error-1025-error-on-ren

반응형