I have problem with pivot table in Laravel,
I made customers
and products
tables and customer_product
table to connect this two but it isn't working.
Below I add this pivot table
Schema::create('customer_product', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->unsignedInteger('product_id');
$table->foreign('product_id')->references('id')->on('products');
$table->decimal('selling_customer_price');
$table->decimal('purchase_customer_price');
$table->decimal('consumed_customer_price');
$table->timestamps();
});
}
Part of my ProductController where I list products and I want show customers products
public function list()
{
return view('products.list', [
'customers' => Customer::all(),
'products' => Product::orderby('name')->get(),
]);
}
and part of simple blade code
<div>
@foreach ($customers as $customer)
<li> {{ $customer->name }} {{ $customer->products }} </li>
@endforeach
</div>
part of Product class
public function customers()
{
return $this->belongsToMany(Customer::class);
}
and part of Customers class
public function products()
{
return $this->hasMany(Product::class);
}
when I type list site I have error about lack of customer_id
column in product
table but I want use my pivot table because I have to use different prices to different customers.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.customer_id' in 'where clause' (SQL: select * from
products
whereproducts
.customer_id
= 1 andproducts
.customer_id
is not null) (View: /home/vagrant/code/resources/views/products/list.blade.php)
customer_product
correctly created? Because$table->foreign('customer_id')->references('id')->on('customers');
should fail.. Assuming the mysql's default engine is InnoDB which only supports foreign keys. – Raymond Nijland