![](/img/trans.png)
[英]SQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Table
[英]Laravel Error : SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists
我無法弄清楚問題是什么,2個表由於某種原因沒有連接,我閱讀了很多文章並嘗試了很多東西仍然無法正常工作。
我想將帖子和類別表鏈接在一起,這樣當我可以顯示在發布的帖子中選擇的類別時。
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->text('description');
$table->integer('category_id');
$table->integer('price');
$table->integer('currency_id');
});
}
類別
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
});
}
這是我得到的錯誤:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists (SQL: create table
categories
(id
bigint unsigned not null auto_increment primary key,created_at
timestamp null,updated_at
timestamp null,name
varchar(255) not null ,post_id
bigint unsigned not null) 默認字符集 utf8mb4 collate 'utf8mb4_unicode_ci')
嘗試使用migrate:refresh
artisan 命令完全刷新您的數據庫。
php artisan migrate:refresh --seed
可能是數據庫遷移在它可以注冊到數據庫的migrations
表中之前運行並失敗。
問題:(到目前為止)
1)如上,一個migrate:refresh
整理出原來的錯誤
2) $table->bigInteger('post_id')->unsigned();
將不起作用,因為posts.id
是integer
而不是bigInteger
。
解決方案:
將您的post_id
定義更改為
$table->integer('post_id')->unsigned();
它說類別表已經存在。 所以你要做的是,如果你在開發環境中,你可以刪除表並嘗試它,或者你可以像下面的命令一樣做。
像這樣運行 artisan,它將刪除所有表並遷移得更新鮮。
php artisan migrate:fresh
這對我有用。
答案很簡單,您必須將帖子表中$table->increments('id')
更改為$table->id()
,因為如消息所述,外鍵必須引用主鍵。
您必須在posts表中使用bigIncrements
而不是integer
因為integer
的長度是4 字節,但bigIncrements
是8 字節,這可能會導致將來出現問題
你可能喜歡使用這條線
$table->foreignId('post_id')->constrained();
反而
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
為簡單起見
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.