透视表laravel的问题

pvabu6sv  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(297)

我有问题的透视表在拉威尔,我做了 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]:未找到列:“where子句”中的1054未知列“products.customer\u id”(sql:select*from) products 哪里 products . customer_id =1和 products . customer_id 不为null)(view:/home/vagrant/code/resources/views/products/list.blade.php)

pnwntuvh

pnwntuvh1#

你说你有多对多的关系,那么你应该有下面这样的关系,从你的评论,你有 selling_customer_price 透视表中必须使用的字段 withPivot . 详情请查收https://laravel.com/docs/5.6/eloquent-relationships#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>

相关问题