【发布时间】:2018-12-16 07:46:44
【问题描述】:
我对 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);
}
当我键入 list site 时,我在 product 表中出现了关于缺少 customer_id 列的错误,但我想使用我的数据透视表,因为我必须对不同的客户使用不同的价格。
SQLSTATE[42S22]:未找到列:1054 未知列 “where 子句”中的“products.customer_id”(SQL:select * from
products其中products.customer_id= 1 和products.customer_id不为空)(查看: /home/vagrant/code/resources/views/products/list.blade.php)
【问题讨论】:
-
SQL 错误提示您忘记使用 customer_id 列更新产品架构... 表
customer_product是否正确创建?因为$table->foreign('customer_id')->references('id')->on('customers');应该会失败。假设mysql的默认引擎是InnoDB,它只支持外键。 -
customer_id 字段是否存在于您的产品表中。
标签: php mysql laravel migration pivot-table