簡體   English   中英

如何傳遞外鍵 laravel

[英]How to pass foreign key laravel

我正在嘗試傳遞外鍵,但遇到此錯誤Base table or view already exists: 1050 Table 'favorites' already exists"我如何將所有外鍵和普通 id 傳遞給它們,例如$table->bigInteger('user_id')->unsigned();

 public function up()
{

    Schema::create('favorites', function (Blueprint $table) {
        $table->Increments('id');
        $table->bigInteger('user_id')->unsigned();
        $table->bigInteger('product_id')->unsigned();
        $table->timestamps();

    });

    Schema::create('favorites', function (Blueprint $table){

        $table->bigInteger('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users');

        $table->bigInteger('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products');
    });

}

public function down()
{
    Schema::dropIfExists('favorites');
}

您要遷移表兩次,在同一遷移中傳遞外鍵

public function up()
{
    Schema::create('favorites', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->bigInteger('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('favorites');
}

希望這可以幫助

請在您的表格中添加此表格字段

public function up()
{
    Schema::create('favorites', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->bigInteger('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products');
        $table->timestamps();
    });
}

其他答案是正確的。 如果您在做之前錯過了所需的任務,請試試這個

1) 移除或刪除已遷移的表

2)在遷移表中,刪除包含名稱“收藏夾”的記錄

3)用這個復制並粘貼“向上” function 里面的代碼

Schema::create('favorites', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->unsigned();
    $table->bigInteger('product_id')->unsigned();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
    $table->foreign('product_id')->references('id')->on('products');

});

4) 再次運行此命令

php artisan migrate

暫無
暫無

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

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