且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Laravel模型关系中显示产品名称

更新时间:2023-11-30 12:41:58

我认为您需要重新排序一些内容

I think you need to reorder some things

// Reorder tables and models
Table Schema and models

Product Model (Table name => 'products')
id
product_name


OrderProduct (Table name => 'order_product')
id
product_id
order_id
price
quantity_id
quantity

Order Model (Table name => 'orders')
id
req_id
amount

// Product Model
public function orders()
{
    return $this->belongsToMany('App\Order')->withPivot('price', 'quantity_id','quantity');
}
// Order Model
public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('price', 'quantity_id','quantity');
}
// Controller
$dataReqorder = Order::where('req_id','=', $shoppingId)->with('products')->get();

// View 
@foreach($dataReqorder as $order)
    <tr class="item{{$order->id}}">
    @foreach($order->products as $product)
        {{$product->id}}<br>
        {{$product->pivot->price}}<br>
        {{$product->pivot->quantity_id}}<br>
        {{$product->pivot->quantity}}<br>
    @endforeach
    <td>{{$order->amount}}</td>
    <td>{{$order->quantity}}</td>
    </tr>
@endforeach

有关更多信息,我建议您查看文档
https://laravel.com/docs/5.6/eloquent-relationships#多对多

For more info I recommend you to see the documentation
https://laravel.com/docs/5.6/eloquent-relationships#many-to-many