如何确定 Laravel 中 belongsToMany 关系中的 pivot-table 名称?

How to determine pivot-table name in belongToMany relationship in Laravel?

我遇到的问题是简单地尝试确定给中间人 table 的正确名称,该中间人用于 Laravel.

中的多对多关系

我在尝试访问 eloquent 关系时收到以下错误:

$product->categories; Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dolstore-laravel.category_product' doesn't exist (SQL: select categories.*, category_product.product_id as pivot_product_id, category_product.category_id as pivot_category_id from categories inner join category_product on categories.id = category_product.category_id where category_product.product_id = 1)'

我的迁移是这样写的:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->timestamps();
        });

        Schema::create('product_category', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('category_id');
            $table->timestamps();

            $table->unique(['product_id', 'category_id']);

            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
    }

似乎我提供的 product_category 的名称不正确,而它应该是 category_product。管理这个的规则是什么?在另一个我实际上成功遵循 Laracasts 教程的示例中,我的迁移编写如下:

    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
        //Pivot Table
        // article_tag

        Schema::create('article_tag', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('article_id');
            $table->unsignedBigInteger('tag_id');
            $table->timestamps();

            $table->unique(['article_id', 'tag_id']);

            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        });
    }

因此它似乎与创建 table 的顺序或定义枢轴 table 的迁移无关。

感谢您帮助我理解这一点。

当您没有在模型中传递 belongsToMany 关系的第二个参数时。因此,Laravel 期望您在创建枢轴 table 时使用其命名约定。他们如何检查?假设您有一个产品和类别 table。

Now, laravel will expect that you had created your pivot table on alphabetical order, they will expect that your pivot table was named category_product considering that the first letter of your category which is 'c' is first than to your table product first letter is 'p'. That is why in your article_tag pivot table it worked right ?

假设您创建了枢轴 table 而未遵循其命名约定。然后你必须将它作为 m 到 m 关系中的第二个参数传递,如下所示。

public function product_categoreis() [
   return $this->belongsToMany('App\Category', 'product_category');
}