我在一次遷移中
$table->unsignedBigInteger('blog_category_id')->nullable();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
我正在通過另一個遷移洗掉這些欄位
$table->dropForeign(['blog_category_id']);
$table->dropColumn('blog_category_id');
第一次一切順利,但是當從資料庫中洗掉資料并進行第二次遷移時,出現錯誤
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'articles' alre ady exists (SQL: create table 'articles' ('id' bigint unsigned not null auto_inc rement primary key) default character set utf8 collate 'utf8_general_ci' engine = InnoDB)
我可以檢查遷移檔案嗎,比如如果該欄位為$table->foreign('blog_category_id') ->references('id')->on('blog_categories')->onDelete('set null');空,那么我們什么都不做。你能在 Laravel 中做到這一點嗎?
uj5u.com熱心網友回復:
我認為與其嘗試搜索此類設定是否存在,不如將change()加到新遷移的末尾,如果您知道該表存在且該列存在。
$table->unsignedBigInteger('blog_category_id')->nullable()->change();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
如果您不知道表或列是否存在,請參見下文。
從您的問題中,我看到您嘗試創建的表已經存在。為了防止此類錯誤,您可以檢查表是否存在并根據合適的內容創建遷移。示例代碼如下:
示例 1:
if(Schema::hasTable('articles')) {
// Do something here is articles exists. (Mostly used for updating migration)
} else {
// Do something if table doesn't exist (Mostly for creating migration)
}
示例 2. 檢查列是否存在(您知道表存在)
if(Schema::hasColumn('articles', 'blog_category_id')) {
$table->unsignedBigInteger('blog_category_id')->nullable()->change();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
} else {
$table->unsignedBigInteger('blog_category_id')->nullable();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
}
示例 3. 檢查列是否存在(多列)
if(Schema::hasColumns('articles', ['blog_category_id', 'another_column'])) {
$table->unsignedBigInteger('blog_category_id')->nullable()->change();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
// More code
} else {
$table->unsignedBigInteger('blog_category_id')->nullable();
$table->foreign('blog_category_id')
->references('id')->on('blog_categories')->onDelete('set null');
// More code
}
如果需要,請查看 Laravel 檔案中的更多資訊 https://laravel.com/docs/8.x/migrations#checking-for-table-column-existence
此外,雖然不是您問題的必要部分,但 Laravel 有一個功能nullOnDelete(),您可以將其鏈接到外鍵部分$table->foreign('blog_category_id') ->references('id')->on('blog_categories')->nullOnDelete();以減少拼寫錯誤的可能性,或者只是添加一些不錯的內容。
uj5u.com熱心網友回復:
我認為你使用 $table->foreign('blog_category_id')->references('id')->on('blog_categories')->onDelete('cascade');
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/335284.html
標籤:拉拉维尔
上一篇:Laravel分頁-呼叫未定義的方法Illuminate\Database\Eloquent\Builder::links()
