Answer the question
In order to leave comments, you need to log in
Why is eloquent looking for another pivot table?
Hello. There are two models
class Product extends Model
{
public function categories(){
return $this->belongsToMany('App\Category');
}
}
class Category extends Model
{
public function children(){
return $this->hasMany(self::class, 'parent_id');
}
}
class CreateProductCategoryTable extends Migration
{
public function up()
{
Schema::create('product_category', function (Blueprint $table) {
$table->BigIncrements('id');
$table->BigInteger('product_id')->unsigned();
$table->BigInteger('category_id')->unsigned();
$table->timestamps();
});
Schema::table('product_category', function (Blueprint $table) {
$table->foreign('product_id')->references('id')->on('products')
->onDelete('cascade')->onUpdate('cascade');
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::table('product_category', function (Blueprint $table){
$table->dropForeign('product_category_product_id_foreign');
$table->dropForeign('product_category_category_id_foreign');
});
Schema::dropIfExists('product_category');
}
public function store(Request $request)
{
$product = Product::create($request->except('categories'));
if($request->has('categories')){
$product->categories()
->attach($request->input('categories'));
}
return redirect()->route('product.index');
}
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.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` = 5) (View: D:\OSPanel\domains\test.local\resources\views\product\_categories.blade.php)
Answer the question
In order to leave comments, you need to log in
The name of the pivot table is formed from the names of the model tables in alphabetical order - category_product, not product_category
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question