簡體   English   中英

Laravel mysql錯誤關系數據庫?

[英]Laravel mysql error relational databases?

語法錯誤或訪問沖突:1072 表中不存在鍵列“collection_id”(SQL:alter table products添加約束products_collection_id_foreign外鍵( collection_id )在刪除級聯時引用collectionsid ))

所以我遇到了這個問題,試圖將產品與具有 collection_id 的集合聯系起來。

這是我的收藏遷移

    class CreateCollectionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('collections', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->string('author');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('collections');
    }
}

這是我的產品遷移

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->integer('price');
            $table->string('src');
            $table->unsignedBigInteger('collection_id');
            $table->foreign('collection_id')->references('id')->on('collections')->onDelete("cascade");
            $table->integer('amount');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

您的遷移是否正確運行您還可以檢查創建表時的遷移順序,如果集合是在產品之前創建的,如果產品是在集合之前創建的,它會拋出此錯誤,因為集合尚未創建,還有一個快捷方式定義外鍵是

$table->foreignId('collection_id')->constrained()->cascadeOnDelete();

您可以通過以下方式進行。

$table->unsignedBigInteger('collection_id');
$table->foreign('collection_id')->references('id')->on('collections')->onDelete("cascade");

還有一件事運行以下命令:

php artisan migrate:fresh 

或者

 php artisan migrate:refresh 

希望您的問題能夠得到解決。或者可以按照以下 URL Laravel 遷移:“外鍵約束格式錯誤”(errno 150)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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