使用eloquent在3个表中的Laravel查询关系

时间:2018-03-18 16:42:14

标签: php laravel laravel-5 eloquent

再次帮助我,

我有3张桌子

Product Table
id
product_name


Productquantity Table
id
prod_id -> product table id
price

Purchaserecord
id
prodquantityid -> productquantity table id
quantity
amount

如何在视图中显示产品名称?我在我的Purchaserecord模型上有这个

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

在我看来

@foreach($dataPurchaseRecord as $Record)
<tr>
<td>{{$Record->productquantity->prod_id}}</td>
<td>{{$Record->quantity}}</td>
<td>{{$Record->price}}</td>
</tr>
@endforeach 

我只是想知道如何显示产品名称而不是productid {{$ Record-&gt; productquantity-&gt; prod_id}}

谢谢

1 个答案:

答案 0 :(得分:0)

在您的控制器中,试试这个:

function viewPurchases(Request $request)
{
    //Perform your query, and end on ->get() to retreive iterable collection.
    $dataPurchaseRecord = Purchaserecord
                           ::with('productquantity')
                           ->where('id', '<', 10)
                           ->get();
    //load your view, and pass the collection to your view. 
    //compact('dataPurchaseRecord') basically results in a key value array like so: 
    //['dataPurchaseRecord' => $dataPurchaseRecord]
    return view('your_viewname', compact('dataPurchaseRecord'));
}

希望有所帮助:)