Laravel Many to Many pivot attach error: "no such table: lists"

Laravel Many to Many pivot attach error: "no such table: lists"

我现在已经开始使用 Pivot table 和 Many to Many 整体关系,所以希望我能了解问题所在。

我在 beersbeer lists 之间有一个 many to many 关系,我有一个自定义 pivot table:

Schema::create('beer_list_pivot', function (Blueprint $table) {
    $table->id();
    $table->foreignId('beer_id')->constrained();
    $table->foreignId('list_id')->constrained();
});

关系看起来像这样:

BeerList 型号:

public function beer()
{
    return $this->belongsToMany(Beer::class, 'beer_list_pivot', 'beer_id', 'list_id');
}

Beer 型号:

public function list()
{
    return $this->belongsToMany(BeerList::class, 'beer_list_pivot', 'list_id', 'beer_id');
}

attach方法是这样使用的:

public function addItem(Request $request, $id)
{
    $beerId = $request->beer;
    $list = BeerList::findOrFail($id);

    $list->beer()->attach($beerId);

    return redirect("/list/" . $list->id);
}

返回错误:

SQLSTATE[HY000]: General error: 1 no such table: main.lists (SQL: insert into "beer_list_pivot" ("beer_id", "list_id") values (1, 1))

知道是什么原因造成的吗?

它说 lists table 未找到

试试这个

Schema::create('beer_list_pivot', function (Blueprint $table) {
     $table->id();
     $table->foreignId('beer_id')->constrained();
     $table->foreignId('list_id')->constrained('beer_lists'); // <= here put your table name
});

并刷新迁移

正如您提到的,您是 pivot tables 的新手,所以让我分享一些超级小技巧,以便您下次减少错误:

  1. 尽量坚持 Laravel standard table naming convention,这样可以减少代码声明和声明内容时可能遗漏的内容。
  2. 您应该安全地删除每个关系的所有定义(删除 table 定义后的任何参数)。
  3. 尽量将 $table->timestamps(); 添加到您的 table 中,因为如果您有 created_atupdated_at 列,您将能够调试任何内容.
  4. 您可以在控制器中利用 implicit model binding

因此,仅针对提示 1,您的最终代码可能如下所示(如果您遵循标准):

迁移

Schema::create('beer_beer_list', function (Blueprint $table) {
    $table->id();
    $table->foreignId('beer_id')->constrained();
    $table->foreignId('list_id')->constrained();

    $table->timestamps();
});

BeerList型号

public function beer()
{
    return $this->belongsToMany(Beer::class);
}

Beer 型号

public function list()
{
    return $this->belongsToMany(BeerList::class);
}

所以,对于提示 4

public function addItem(Request $request, BeerList $list)
{
    $beerId = $request->beer;

    $list->beer()->attach($beerId);

    return redirect("/list/" . $list->id);
}

你的路线应该是这样的:

Route::post('/beer/{list}', [BeerListController::class, 'addItem']);

最重要的是 {list} 或任何你写的 {slug} 必须匹配 BeerList $listBeerList $slug (变量名)而且你必须键入提示它。 documentation 解释得很好。