在Laravel模型关系中显示产品名称 [英] Show Product Name in Laravel Model Relationship

查看:65
本文介绍了在Laravel模型关系中显示产品名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能再帮我一次吗?我有3张桌子

Can you help me again? I have 3 tables

Product Table
id
product_name


Productquantity Table
id
item_id
price

Orders
id
req_id
quantity_id
quantity
amount

如何在CartView中获得产品名称?我的代码中只有这个

How can I get the product name in my CartView? I only have this in my code

订单模型

public function product()
    {
        return $this->belongsTO('App\Productquantity', 'item_id', 'id');
    }

我的控制器

 $dataReqorder = Reqorder::where('req_id','=', $shoppingId)->with('product')->get();

我的观点

@foreach($dataReqorder as $order)
<tr class="item{{$order->id}}">
<td> <a href="products/{{$order->id}}" class="name">{{$order->product->prod_id}}</a> </td>
<td>{{$order->amount}}</td>
<td>{{$order->quantity}}</td>
</tr>
@endforeach

我希望此{{$ order-> product-> prod_id}}应该是产品的名称,而不是产品ID.我只是不知道如何在模型和控制器上使用它..请帮助

I want this {{$order->product->prod_id}} should be the name of the product instead of the product ID.. I just do not know how to do it on model and controller.. Please help

推荐答案

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

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

这篇关于在Laravel模型关系中显示产品名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆