簡體   English   中英

Laravel 錯誤:SQLSTATE[42S01]:基表或視圖已存在:1050 表“類別”已存在

[英]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.idinteger而不是bigInteger

解決方案:

將您的post_id定義更改為

$table->integer('post_id')->unsigned();

它說類別表已經存在。 所以你要做的是,如果你在開發環境中,你可以刪除表並嘗試它,或者你可以像下面的命令一樣做。

像這樣運行 artisan,它將刪除所有表並遷移得更新鮮。

php artisan migrate:fresh

這對我有用。

答案很簡單,您必須將帖子表中$table->increments('id')更改為$table->id() ,因為如消息所述,外鍵必須引用主鍵。

這里有一些提示給你

  • 您必須在posts表中使用bigIncrements而不是integer因為integer的長度是4 字節,但bigIncrements8 字節,這可能會導致將來出現問題

  • 你可能喜歡使用這條線

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM