I am having the issue of simply trying to determine the correct name to give to the intermediary table used for many to many relationships in Laravel.
I received the following error upon attempting to access an eloquent relationship:
$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
aspivot_product_id
,category_product
.category_id
aspivot_category_id
fromcategories
inner joincategory_product
oncategories
.id
=category_product
.category_id
wherecategory_product
.product_id
= 1)'
My migration is written as follows:
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');
});
}
It seems that I provided the incorrect name of product_category
when it should have been category_product
. What is the rule governing this? In another example where I actually succeeded following a tutorial on Laracasts, my migration was written as follows:
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');
});
}
Therefore it does not appear to be related to the order in which the tables are created or the migration within which the pivot table is defined.
Thank you for helping me understand this.