我在Laravel中的数据透视表有问题,
我制作了customers
和products
表以及customer_product
表来连接这两个表,但是它不起作用。
在下面添加此数据透视表
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();
});
}
我的ProductController的一部分,我在其中列出产品并希望向客户展示产品
public function list()
{
return view('products.list', [
'customers' => Customer::all(),
'products' => Product::orderby('name')->get(),
]);
}
和简单刀片代码的一部分
<div>
@foreach ($customers as $customer)
<li> {{ $customer->name }} {{ $customer->products }} </li>
@endforeach
</div>
产品类的一部分
public function customers()
{
return $this->belongsToMany(Customer::class);
}
和部分客户类
public function products()
{
return $this->hasMany(Product::class);
}
当我输入列表网站时,我对customer_id
表中缺少product
列存在错误,但是我想使用数据透视表,因为我必须对不同的客户使用不同的价格。
SQLSTATE [42S22]:找不到列:1054未知列 “ where子句”中的“ products.customer_id”(SQL:从*中选择*
products
,其中products
。customer_id
= 1且products
。customer_id
不为null)(查看: /home/vagrant/code/resources/views/products/list.blade.php)
答案 0 :(得分:1)
您说您有很多对很多的关系,那么您应该具有下面的关系,并且从您的注释中,您必须使用selling_customer_price
在数据透视表中有withPivot
字段。有关详细信息,请检查https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
产品类的一部分
public function customers()
{
return $this->belongsToMany(Customer::class)->withPivot('selling_customer_price');
}
和部分客户类
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('selling_customer_price');
}
然后像这样获取它
public function list()
{
return view('products.list', [
'customers' => Customer::with('products')->all(),
'products' => Product::orderby('name')->get(),
]);
}
在视图中
<div>
<ul>
@foreach ($customers as $customer)
<li> {{ $customer->name }} </li>
<ul>
@foreach ($customer->products as $product)
<li> {{ $product->name }} </li>
<li> {{ $product->pivot->selling_customer_price }} </li>
@endforeach
</ul>
@endforeach
</ul>
</div>