gpt4 book ai didi

php - 数据透视表 Laravel 问题

转载 作者:行者123 更新时间:2023-11-29 07:31:03 26 4
gpt4 key购买 nike

我对 Laravel 中的数据透视表有疑问,我制作了 customersproducts 表以及 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(),

]);
}

和部分简单 Blade 代码

<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]: Column not found: 1054 Unknown column 'products.customer_id' in 'where clause' (SQL: select * from products where products.customer_id = 1 and products.customer_id is not null) (View: /home/vagrant/code/resources/views/products/list.blade.php)

最佳答案

你说你有多对多关系,那么你应该有如下关系,从你的评论中,你在数据透视表中有 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(),

]);
}

在 View 中

<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>

关于php - 数据透视表 Laravel 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51231764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com