【问题标题】:Laravel Query Relationship in 3 tables using eloquentLaravel 使用 eloquent 查询 3 个表中的关系
【发布时间】:2018-03-18 16:42:13
【问题描述】:

再次帮助我,

我有 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->productquantity->prod_id}}

谢谢

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

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

    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'));
    }
    

    希望对你有帮助:)

    【讨论】:

    • 我的控制器上已经有了这个,但是我只能检索产品 ID 而不是其他相关产品表上的名称。
    • 如果您想查询与您的购买记录相关的产品数量,您可以将 ::with('productquantity') 替换为 ::with(['productquantity' => function($query){$查询->where('id', '
    猜你喜欢
    • 2021-10-02
    • 2021-09-25
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2021-05-06
    • 2014-10-31
    • 2013-10-03
    • 2017-07-19
    相关资源
    最近更新 更多