as you don't follow convention you probably need to fully specify foreign keys in each relation
Jul 27, 2017
7
Level 3
belongsToMany fires query with id 0
Hi, got the following migrations:
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique()->index();
$table->string('name')->unique();
$table->string('teaser', 350);
$table->integer('product_category_id')->unsigned()->nullable();
$table->integer('image_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('product_category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->foreign('image_id')->references('id')->on('images')->onDelete('set null');
});
Schema::create('product_to_category', function(Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('product_category_id')->unsigned();
$table->timestamps();
$table->foreign('product_category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductCategory extends Model
{
public function products()
{
return $this->belongsToMany(Product::class, 'product_to_category');
}
}
The query is correct, but it set's the wrong id (0 instead of 1):
select `products`.*, `product_to_category`.`product_category_id` as `pivot_product_category_id`, `product_to_category`.`product_id` as `pivot_product_id` from `products` inner join `product_to_category` on `products`.`id` = `product_to_category`.`product_id` where `product_to_category`.`product_category_id` in (0)
Build a lot of Laravel applications, but I have no clue what's up here. Any idea?
Please or to participate in this conversation.